blob: 800f9832498329c6e87c603c05035008d94cc354 [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"
David Majnemere9f6f332013-09-16 22:44:20 +000024#include "clang/Basic/TargetInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000025#include "clang/Lex/Preprocessor.h"
26#include "clang/Sema/Initialization.h"
27#include "clang/Sema/Lookup.h"
28#include "clang/Sema/SemaInternal.h"
29#include "clang/Sema/Template.h"
30#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor661b4932010-09-12 04:28:07 +000031#include "llvm/ADT/DenseSet.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000032#include "llvm/ADT/STLExtras.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000033#include "llvm/ADT/SmallPtrSet.h"
Richard Smithb8590f32012-05-07 09:03:25 +000034#include "llvm/ADT/SmallString.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000035#include <algorithm>
36
37namespace clang {
John McCall2a7fb272010-08-25 05:32:35 +000038using namespace sema;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000039
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000040/// A convenience routine for creating a decayed reference to a function.
John Wiegley429bb272011-04-08 18:41:53 +000041static ExprResult
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000042CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
43 bool HadMultipleCandidates,
Douglas Gregor5b8968c2011-07-15 16:25:15 +000044 SourceLocation Loc = SourceLocation(),
45 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Richard Smith82f145d2013-05-04 06:44:46 +000046 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
Faisal Valid570a922013-06-15 11:54:37 +000047 return ExprError();
48 // If FoundDecl is different from Fn (such as if one is a template
49 // and the other a specialization), make sure DiagnoseUseOfDecl is
50 // called on both.
51 // FIXME: This would be more comprehensively addressed by modifying
52 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
53 // being used.
54 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
Richard Smith82f145d2013-05-04 06:44:46 +000055 return ExprError();
John McCallf4b88a42012-03-10 09:33:50 +000056 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000057 VK_LValue, Loc, LocInfo);
58 if (HadMultipleCandidates)
59 DRE->setHadMultipleCandidates(true);
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000060
61 S.MarkDeclRefReferenced(DRE);
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000062
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000063 ExprResult E = S.Owned(DRE);
John Wiegley429bb272011-04-08 18:41:53 +000064 E = S.DefaultFunctionArrayConversion(E.take());
65 if (E.isInvalid())
66 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000067 return E;
John McCallf89e55a2010-11-18 06:31:45 +000068}
69
John McCall120d63c2010-08-24 20:38:10 +000070static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
71 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +000072 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +000073 bool CStyle,
74 bool AllowObjCWritebackConversion);
Sam Panzerd0125862012-08-16 02:38:47 +000075
Fariborz Jahaniand97f5582011-03-23 19:50:54 +000076static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
77 QualType &ToType,
78 bool InOverloadResolution,
79 StandardConversionSequence &SCS,
80 bool CStyle);
John McCall120d63c2010-08-24 20:38:10 +000081static OverloadingResult
82IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
83 UserDefinedConversionSequence& User,
84 OverloadCandidateSet& Conversions,
85 bool AllowExplicit);
86
87
88static ImplicitConversionSequence::CompareKind
89CompareStandardConversionSequences(Sema &S,
90 const StandardConversionSequence& SCS1,
91 const StandardConversionSequence& SCS2);
92
93static ImplicitConversionSequence::CompareKind
94CompareQualificationConversions(Sema &S,
95 const StandardConversionSequence& SCS1,
96 const StandardConversionSequence& SCS2);
97
98static ImplicitConversionSequence::CompareKind
99CompareDerivedToBaseConversions(Sema &S,
100 const StandardConversionSequence& SCS1,
101 const StandardConversionSequence& SCS2);
102
103
104
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000105/// GetConversionCategory - Retrieve the implicit conversion
106/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +0000107ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000108GetConversionCategory(ImplicitConversionKind Kind) {
109 static const ImplicitConversionCategory
110 Category[(int)ICK_Num_Conversion_Kinds] = {
111 ICC_Identity,
112 ICC_Lvalue_Transformation,
113 ICC_Lvalue_Transformation,
114 ICC_Lvalue_Transformation,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000115 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000116 ICC_Qualification_Adjustment,
117 ICC_Promotion,
118 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000119 ICC_Promotion,
120 ICC_Conversion,
121 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000122 ICC_Conversion,
123 ICC_Conversion,
124 ICC_Conversion,
125 ICC_Conversion,
126 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000127 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000128 ICC_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000129 ICC_Conversion,
130 ICC_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000131 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000132 ICC_Conversion
133 };
134 return Category[(int)Kind];
135}
136
137/// GetConversionRank - Retrieve the implicit conversion rank
138/// corresponding to the given implicit conversion kind.
139ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
140 static const ImplicitConversionRank
141 Rank[(int)ICK_Num_Conversion_Kinds] = {
142 ICR_Exact_Match,
143 ICR_Exact_Match,
144 ICR_Exact_Match,
145 ICR_Exact_Match,
146 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000147 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000148 ICR_Promotion,
149 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000150 ICR_Promotion,
151 ICR_Conversion,
152 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000153 ICR_Conversion,
154 ICR_Conversion,
155 ICR_Conversion,
156 ICR_Conversion,
157 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000158 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000159 ICR_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000160 ICR_Conversion,
161 ICR_Conversion,
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000162 ICR_Complex_Real_Conversion,
163 ICR_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000164 ICR_Conversion,
165 ICR_Writeback_Conversion
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000166 };
167 return Rank[(int)Kind];
168}
169
170/// GetImplicitConversionName - Return the name of this kind of
171/// implicit conversion.
172const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +0000173 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000174 "No conversion",
175 "Lvalue-to-rvalue",
176 "Array-to-pointer",
177 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +0000178 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000179 "Qualification",
180 "Integral promotion",
181 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000182 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000183 "Integral conversion",
184 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000185 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000186 "Floating-integral conversion",
187 "Pointer conversion",
188 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000189 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000190 "Compatible-types conversion",
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000191 "Derived-to-base conversion",
192 "Vector conversion",
193 "Vector splat",
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000194 "Complex-real conversion",
195 "Block Pointer conversion",
196 "Transparent Union Conversion"
John McCallf85e1932011-06-15 23:02:42 +0000197 "Writeback conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000198 };
199 return Name[Kind];
200}
201
Douglas Gregor60d62c22008-10-31 16:23:19 +0000202/// StandardConversionSequence - Set the standard conversion
203/// sequence to the identity conversion.
204void StandardConversionSequence::setAsIdentityConversion() {
205 First = ICK_Identity;
206 Second = ICK_Identity;
207 Third = ICK_Identity;
Douglas Gregora9bff302010-02-28 18:30:25 +0000208 DeprecatedStringLiteralToCharPtr = false;
John McCallf85e1932011-06-15 23:02:42 +0000209 QualificationIncludesObjCLifetime = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000210 ReferenceBinding = false;
211 DirectBinding = false;
Douglas Gregor440a4832011-01-26 14:52:12 +0000212 IsLvalueReference = true;
213 BindsToFunctionLvalue = false;
214 BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +0000215 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +0000216 ObjCLifetimeConversionBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000217 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000218}
219
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000220/// getRank - Retrieve the rank of this standard conversion sequence
221/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
222/// implicit conversions.
223ImplicitConversionRank StandardConversionSequence::getRank() const {
224 ImplicitConversionRank Rank = ICR_Exact_Match;
225 if (GetConversionRank(First) > Rank)
226 Rank = GetConversionRank(First);
227 if (GetConversionRank(Second) > Rank)
228 Rank = GetConversionRank(Second);
229 if (GetConversionRank(Third) > Rank)
230 Rank = GetConversionRank(Third);
231 return Rank;
232}
233
234/// isPointerConversionToBool - Determines whether this conversion is
235/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000236/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000237/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000238bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000239 // Note that FromType has not necessarily been transformed by the
240 // array-to-pointer or function-to-pointer implicit conversions, so
241 // check for their presence as well as checking whether FromType is
242 // a pointer.
Douglas Gregorad323a82010-01-27 03:51:04 +0000243 if (getToType(1)->isBooleanType() &&
John McCallddb0ce72010-06-11 10:04:22 +0000244 (getFromType()->isPointerType() ||
245 getFromType()->isObjCObjectPointerType() ||
246 getFromType()->isBlockPointerType() ||
Anders Carlssonc8df0b62010-11-05 00:12:09 +0000247 getFromType()->isNullPtrType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000248 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
249 return true;
250
251 return false;
252}
253
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000254/// isPointerConversionToVoidPointer - Determines whether this
255/// conversion is a conversion of a pointer to a void pointer. This is
256/// used as part of the ranking of standard conversion sequences (C++
257/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000258bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000259StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000260isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000261 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000262 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000263
264 // Note that FromType has not necessarily been transformed by the
265 // array-to-pointer implicit conversion, so check for its presence
266 // and redo the conversion to get a pointer.
267 if (First == ICK_Array_To_Pointer)
268 FromType = Context.getArrayDecayedType(FromType);
269
Douglas Gregorf9af5242011-04-15 20:45:44 +0000270 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000271 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000272 return ToPtrType->getPointeeType()->isVoidType();
273
274 return false;
275}
276
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000277/// Skip any implicit casts which could be either part of a narrowing conversion
278/// or after one in an implicit conversion.
279static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
280 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
281 switch (ICE->getCastKind()) {
282 case CK_NoOp:
283 case CK_IntegralCast:
284 case CK_IntegralToBoolean:
285 case CK_IntegralToFloating:
286 case CK_FloatingToIntegral:
287 case CK_FloatingToBoolean:
288 case CK_FloatingCast:
289 Converted = ICE->getSubExpr();
290 continue;
291
292 default:
293 return Converted;
294 }
295 }
296
297 return Converted;
298}
299
300/// Check if this standard conversion sequence represents a narrowing
301/// conversion, according to C++11 [dcl.init.list]p7.
302///
303/// \param Ctx The AST context.
304/// \param Converted The result of applying this standard conversion sequence.
305/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
306/// value of the expression prior to the narrowing conversion.
Richard Smithf6028062012-03-23 23:55:39 +0000307/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
308/// type of the expression prior to the narrowing conversion.
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000309NarrowingKind
Richard Smith8ef7b202012-01-18 23:55:52 +0000310StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
311 const Expr *Converted,
Richard Smithf6028062012-03-23 23:55:39 +0000312 APValue &ConstantValue,
313 QualType &ConstantType) const {
David Blaikie4e4d0842012-03-11 07:00:24 +0000314 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000315
316 // C++11 [dcl.init.list]p7:
317 // A narrowing conversion is an implicit conversion ...
318 QualType FromType = getToType(0);
319 QualType ToType = getToType(1);
320 switch (Second) {
321 // -- from a floating-point type to an integer type, or
322 //
323 // -- from an integer type or unscoped enumeration type to a floating-point
324 // type, except where the source is a constant expression and the actual
325 // value after conversion will fit into the target type and will produce
326 // the original value when converted back to the original type, or
327 case ICK_Floating_Integral:
328 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
329 return NK_Type_Narrowing;
330 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
331 llvm::APSInt IntConstantValue;
332 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
333 if (Initializer &&
334 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
335 // Convert the integer to the floating type.
336 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
337 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
338 llvm::APFloat::rmNearestTiesToEven);
339 // And back.
340 llvm::APSInt ConvertedValue = IntConstantValue;
341 bool ignored;
342 Result.convertToInteger(ConvertedValue,
343 llvm::APFloat::rmTowardZero, &ignored);
344 // If the resulting value is different, this was a narrowing conversion.
345 if (IntConstantValue != ConvertedValue) {
346 ConstantValue = APValue(IntConstantValue);
Richard Smithf6028062012-03-23 23:55:39 +0000347 ConstantType = Initializer->getType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000348 return NK_Constant_Narrowing;
349 }
350 } else {
351 // Variables are always narrowings.
352 return NK_Variable_Narrowing;
353 }
354 }
355 return NK_Not_Narrowing;
356
357 // -- from long double to double or float, or from double to float, except
358 // where the source is a constant expression and the actual value after
359 // conversion is within the range of values that can be represented (even
360 // if it cannot be represented exactly), or
361 case ICK_Floating_Conversion:
362 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
363 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
364 // FromType is larger than ToType.
365 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
366 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
367 // Constant!
368 assert(ConstantValue.isFloat());
369 llvm::APFloat FloatVal = ConstantValue.getFloat();
370 // Convert the source value into the target type.
371 bool ignored;
372 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
373 Ctx.getFloatTypeSemantics(ToType),
374 llvm::APFloat::rmNearestTiesToEven, &ignored);
375 // If there was no overflow, the source value is within the range of
376 // values that can be represented.
Richard Smithf6028062012-03-23 23:55:39 +0000377 if (ConvertStatus & llvm::APFloat::opOverflow) {
378 ConstantType = Initializer->getType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000379 return NK_Constant_Narrowing;
Richard Smithf6028062012-03-23 23:55:39 +0000380 }
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000381 } else {
382 return NK_Variable_Narrowing;
383 }
384 }
385 return NK_Not_Narrowing;
386
387 // -- from an integer type or unscoped enumeration type to an integer type
388 // that cannot represent all the values of the original type, except where
389 // the source is a constant expression and the actual value after
390 // conversion will fit into the target type and will produce the original
391 // value when converted back to the original type.
392 case ICK_Boolean_Conversion: // Bools are integers too.
393 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
394 // Boolean conversions can be from pointers and pointers to members
395 // [conv.bool], and those aren't considered narrowing conversions.
396 return NK_Not_Narrowing;
397 } // Otherwise, fall through to the integral case.
398 case ICK_Integral_Conversion: {
399 assert(FromType->isIntegralOrUnscopedEnumerationType());
400 assert(ToType->isIntegralOrUnscopedEnumerationType());
401 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
402 const unsigned FromWidth = Ctx.getIntWidth(FromType);
403 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
404 const unsigned ToWidth = Ctx.getIntWidth(ToType);
405
406 if (FromWidth > ToWidth ||
Richard Smithcd65f492012-06-13 01:07:41 +0000407 (FromWidth == ToWidth && FromSigned != ToSigned) ||
408 (FromSigned && !ToSigned)) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000409 // Not all values of FromType can be represented in ToType.
410 llvm::APSInt InitializerValue;
411 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smithcd65f492012-06-13 01:07:41 +0000412 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
413 // Such conversions on variables are always narrowing.
414 return NK_Variable_Narrowing;
Richard Smith5d7700e2012-06-19 21:28:35 +0000415 }
416 bool Narrowing = false;
417 if (FromWidth < ToWidth) {
Richard Smithcd65f492012-06-13 01:07:41 +0000418 // Negative -> unsigned is narrowing. Otherwise, more bits is never
419 // narrowing.
420 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith5d7700e2012-06-19 21:28:35 +0000421 Narrowing = true;
Richard Smithcd65f492012-06-13 01:07:41 +0000422 } else {
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000423 // Add a bit to the InitializerValue so we don't have to worry about
424 // signed vs. unsigned comparisons.
425 InitializerValue = InitializerValue.extend(
426 InitializerValue.getBitWidth() + 1);
427 // Convert the initializer to and from the target width and signed-ness.
428 llvm::APSInt ConvertedValue = InitializerValue;
429 ConvertedValue = ConvertedValue.trunc(ToWidth);
430 ConvertedValue.setIsSigned(ToSigned);
431 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
432 ConvertedValue.setIsSigned(InitializerValue.isSigned());
433 // If the result is different, this was a narrowing conversion.
Richard Smith5d7700e2012-06-19 21:28:35 +0000434 if (ConvertedValue != InitializerValue)
435 Narrowing = true;
436 }
437 if (Narrowing) {
438 ConstantType = Initializer->getType();
439 ConstantValue = APValue(InitializerValue);
440 return NK_Constant_Narrowing;
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000441 }
442 }
443 return NK_Not_Narrowing;
444 }
445
446 default:
447 // Other kinds of conversions are not narrowings.
448 return NK_Not_Narrowing;
449 }
450}
451
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000452/// DebugPrint - Print this standard conversion sequence to standard
453/// error. Useful for debugging overloading issues.
454void StandardConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000455 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000456 bool PrintedSomething = false;
457 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000458 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000459 PrintedSomething = true;
460 }
461
462 if (Second != ICK_Identity) {
463 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000464 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000465 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000466 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000467
468 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000469 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000470 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000471 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000472 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000473 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000474 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000475 PrintedSomething = true;
476 }
477
478 if (Third != ICK_Identity) {
479 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000480 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000481 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000482 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000483 PrintedSomething = true;
484 }
485
486 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000487 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000488 }
489}
490
491/// DebugPrint - Print this user-defined conversion sequence to standard
492/// error. Useful for debugging overloading issues.
493void UserDefinedConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000494 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000495 if (Before.First || Before.Second || Before.Third) {
496 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000497 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000498 }
Sebastian Redlcc7a6482011-11-01 15:53:09 +0000499 if (ConversionFunction)
500 OS << '\'' << *ConversionFunction << '\'';
501 else
502 OS << "aggregate initialization";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000503 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000504 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000505 After.DebugPrint();
506 }
507}
508
509/// DebugPrint - Print this implicit conversion sequence to standard
510/// error. Useful for debugging overloading issues.
511void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000512 raw_ostream &OS = llvm::errs();
Richard Smith798186a2013-09-06 22:30:28 +0000513 if (isStdInitializerListElement())
514 OS << "Worst std::initializer_list element conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000515 switch (ConversionKind) {
516 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000517 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000518 Standard.DebugPrint();
519 break;
520 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000521 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000522 UserDefined.DebugPrint();
523 break;
524 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000525 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000526 break;
John McCall1d318332010-01-12 00:44:57 +0000527 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000528 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000529 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000530 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000531 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000532 break;
533 }
534
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000535 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000536}
537
John McCall1d318332010-01-12 00:44:57 +0000538void AmbiguousConversionSequence::construct() {
539 new (&conversions()) ConversionSet();
540}
541
542void AmbiguousConversionSequence::destruct() {
543 conversions().~ConversionSet();
544}
545
546void
547AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
548 FromTypePtr = O.FromTypePtr;
549 ToTypePtr = O.ToTypePtr;
550 new (&conversions()) ConversionSet(O.conversions());
551}
552
Douglas Gregora9333192010-05-08 17:41:32 +0000553namespace {
Larisse Voufo43847122013-07-19 23:00:19 +0000554 // Structure used by DeductionFailureInfo to store
Richard Smith29805ca2013-01-31 05:19:49 +0000555 // template argument information.
556 struct DFIArguments {
Douglas Gregora9333192010-05-08 17:41:32 +0000557 TemplateArgument FirstArg;
558 TemplateArgument SecondArg;
559 };
Larisse Voufo43847122013-07-19 23:00:19 +0000560 // Structure used by DeductionFailureInfo to store
Richard Smith29805ca2013-01-31 05:19:49 +0000561 // template parameter and template argument information.
562 struct DFIParamWithArguments : DFIArguments {
563 TemplateParameter Param;
564 };
Douglas Gregora9333192010-05-08 17:41:32 +0000565}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000566
Douglas Gregora9333192010-05-08 17:41:32 +0000567/// \brief Convert from Sema's representation of template deduction information
568/// to the form used in overload-candidate information.
Larisse Voufo43847122013-07-19 23:00:19 +0000569DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context,
570 Sema::TemplateDeductionResult TDK,
571 TemplateDeductionInfo &Info) {
572 DeductionFailureInfo Result;
Douglas Gregora9333192010-05-08 17:41:32 +0000573 Result.Result = static_cast<unsigned>(TDK);
Richard Smithb8590f32012-05-07 09:03:25 +0000574 Result.HasDiagnostic = false;
Douglas Gregora9333192010-05-08 17:41:32 +0000575 Result.Data = 0;
576 switch (TDK) {
577 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000578 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000579 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000580 case Sema::TDK_TooManyArguments:
581 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000582 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000583
Douglas Gregora9333192010-05-08 17:41:32 +0000584 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000585 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000586 Result.Data = Info.Param.getOpaqueValue();
587 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000588
Richard Smith29805ca2013-01-31 05:19:49 +0000589 case Sema::TDK_NonDeducedMismatch: {
590 // FIXME: Should allocate from normal heap so that we can free this later.
591 DFIArguments *Saved = new (Context) DFIArguments;
592 Saved->FirstArg = Info.FirstArg;
593 Saved->SecondArg = Info.SecondArg;
594 Result.Data = Saved;
595 break;
596 }
597
Douglas Gregora9333192010-05-08 17:41:32 +0000598 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000599 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000600 // FIXME: Should allocate from normal heap so that we can free this later.
601 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000602 Saved->Param = Info.Param;
603 Saved->FirstArg = Info.FirstArg;
604 Saved->SecondArg = Info.SecondArg;
605 Result.Data = Saved;
606 break;
607 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000608
Douglas Gregora9333192010-05-08 17:41:32 +0000609 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000610 Result.Data = Info.take();
Richard Smithb8590f32012-05-07 09:03:25 +0000611 if (Info.hasSFINAEDiagnostic()) {
612 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
613 SourceLocation(), PartialDiagnostic::NullDiagnostic());
614 Info.takeSFINAEDiagnostic(*Diag);
615 Result.HasDiagnostic = true;
616 }
Douglas Gregorec20f462010-05-08 20:07:26 +0000617 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000618
Douglas Gregora9333192010-05-08 17:41:32 +0000619 case Sema::TDK_FailedOverloadResolution:
Richard Smith0efa62f2013-01-31 04:03:12 +0000620 Result.Data = Info.Expression;
621 break;
622
Richard Smith29805ca2013-01-31 05:19:49 +0000623 case Sema::TDK_MiscellaneousDeductionFailure:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000624 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000625 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000626
Douglas Gregora9333192010-05-08 17:41:32 +0000627 return Result;
628}
John McCall1d318332010-01-12 00:44:57 +0000629
Larisse Voufo43847122013-07-19 23:00:19 +0000630void DeductionFailureInfo::Destroy() {
Douglas Gregora9333192010-05-08 17:41:32 +0000631 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
632 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000633 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000634 case Sema::TDK_InstantiationDepth:
635 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000636 case Sema::TDK_TooManyArguments:
637 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000638 case Sema::TDK_InvalidExplicitArguments:
Richard Smith29805ca2013-01-31 05:19:49 +0000639 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000640 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000641
Douglas Gregora9333192010-05-08 17:41:32 +0000642 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000643 case Sema::TDK_Underqualified:
Richard Smith29805ca2013-01-31 05:19:49 +0000644 case Sema::TDK_NonDeducedMismatch:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000645 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000646 Data = 0;
647 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000648
649 case Sema::TDK_SubstitutionFailure:
Richard Smithb8590f32012-05-07 09:03:25 +0000650 // FIXME: Destroy the template argument list?
Douglas Gregorec20f462010-05-08 20:07:26 +0000651 Data = 0;
Richard Smithb8590f32012-05-07 09:03:25 +0000652 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
653 Diag->~PartialDiagnosticAt();
654 HasDiagnostic = false;
655 }
Douglas Gregorec20f462010-05-08 20:07:26 +0000656 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000657
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000658 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000659 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000660 break;
661 }
662}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000663
Larisse Voufo43847122013-07-19 23:00:19 +0000664PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smithb8590f32012-05-07 09:03:25 +0000665 if (HasDiagnostic)
666 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
667 return 0;
668}
669
Larisse Voufo43847122013-07-19 23:00:19 +0000670TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregora9333192010-05-08 17:41:32 +0000671 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
672 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000673 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000674 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000675 case Sema::TDK_TooManyArguments:
676 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000677 case Sema::TDK_SubstitutionFailure:
Richard Smith29805ca2013-01-31 05:19:49 +0000678 case Sema::TDK_NonDeducedMismatch:
679 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000680 return TemplateParameter();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000681
Douglas Gregora9333192010-05-08 17:41:32 +0000682 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000683 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000684 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregora9333192010-05-08 17:41:32 +0000685
686 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000687 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000688 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000689
Douglas Gregora9333192010-05-08 17:41:32 +0000690 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000691 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000692 break;
693 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000694
Douglas Gregora9333192010-05-08 17:41:32 +0000695 return TemplateParameter();
696}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000697
Larisse Voufo43847122013-07-19 23:00:19 +0000698TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregorec20f462010-05-08 20:07:26 +0000699 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith29805ca2013-01-31 05:19:49 +0000700 case Sema::TDK_Success:
701 case Sema::TDK_Invalid:
702 case Sema::TDK_InstantiationDepth:
703 case Sema::TDK_TooManyArguments:
704 case Sema::TDK_TooFewArguments:
705 case Sema::TDK_Incomplete:
706 case Sema::TDK_InvalidExplicitArguments:
707 case Sema::TDK_Inconsistent:
708 case Sema::TDK_Underqualified:
709 case Sema::TDK_NonDeducedMismatch:
710 case Sema::TDK_FailedOverloadResolution:
711 return 0;
Douglas Gregorec20f462010-05-08 20:07:26 +0000712
Richard Smith29805ca2013-01-31 05:19:49 +0000713 case Sema::TDK_SubstitutionFailure:
714 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000715
Richard Smith29805ca2013-01-31 05:19:49 +0000716 // Unhandled
717 case Sema::TDK_MiscellaneousDeductionFailure:
718 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000719 }
720
721 return 0;
722}
723
Larisse Voufo43847122013-07-19 23:00:19 +0000724const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregora9333192010-05-08 17:41:32 +0000725 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
726 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000727 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000728 case Sema::TDK_InstantiationDepth:
729 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000730 case Sema::TDK_TooManyArguments:
731 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000732 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000733 case Sema::TDK_SubstitutionFailure:
Richard Smith29805ca2013-01-31 05:19:49 +0000734 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000735 return 0;
736
Douglas Gregora9333192010-05-08 17:41:32 +0000737 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000738 case Sema::TDK_Underqualified:
Richard Smith29805ca2013-01-31 05:19:49 +0000739 case Sema::TDK_NonDeducedMismatch:
740 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000741
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000742 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000743 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000744 break;
745 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000746
Douglas Gregora9333192010-05-08 17:41:32 +0000747 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000748}
Douglas Gregora9333192010-05-08 17:41:32 +0000749
Larisse Voufo43847122013-07-19 23:00:19 +0000750const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregora9333192010-05-08 17:41:32 +0000751 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
752 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000753 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000754 case Sema::TDK_InstantiationDepth:
755 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000756 case Sema::TDK_TooManyArguments:
757 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000758 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000759 case Sema::TDK_SubstitutionFailure:
Richard Smith29805ca2013-01-31 05:19:49 +0000760 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000761 return 0;
762
Douglas Gregora9333192010-05-08 17:41:32 +0000763 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000764 case Sema::TDK_Underqualified:
Richard Smith29805ca2013-01-31 05:19:49 +0000765 case Sema::TDK_NonDeducedMismatch:
766 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000767
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000768 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000769 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000770 break;
771 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000772
Douglas Gregora9333192010-05-08 17:41:32 +0000773 return 0;
774}
775
Larisse Voufo43847122013-07-19 23:00:19 +0000776Expr *DeductionFailureInfo::getExpr() {
Richard Smith0efa62f2013-01-31 04:03:12 +0000777 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
778 Sema::TDK_FailedOverloadResolution)
779 return static_cast<Expr*>(Data);
780
781 return 0;
782}
783
Benjamin Kramerf5b132f2012-10-09 15:52:25 +0000784void OverloadCandidateSet::destroyCandidates() {
Richard Smithe3898ac2012-07-18 23:52:59 +0000785 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer9e2822b2012-01-14 20:16:52 +0000786 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
787 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smithe3898ac2012-07-18 23:52:59 +0000788 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
789 i->DeductionFailure.Destroy();
790 }
Benjamin Kramerf5b132f2012-10-09 15:52:25 +0000791}
792
793void OverloadCandidateSet::clear() {
794 destroyCandidates();
Benjamin Kramer314f5542012-01-14 19:31:39 +0000795 NumInlineSequences = 0;
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +0000796 Candidates.clear();
Douglas Gregora9333192010-05-08 17:41:32 +0000797 Functions.clear();
798}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000799
John McCall5acb0c92011-10-17 18:40:02 +0000800namespace {
801 class UnbridgedCastsSet {
802 struct Entry {
803 Expr **Addr;
804 Expr *Saved;
805 };
806 SmallVector<Entry, 2> Entries;
807
808 public:
809 void save(Sema &S, Expr *&E) {
810 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
811 Entry entry = { &E, E };
812 Entries.push_back(entry);
813 E = S.stripARCUnbridgedCast(E);
814 }
815
816 void restore() {
817 for (SmallVectorImpl<Entry>::iterator
818 i = Entries.begin(), e = Entries.end(); i != e; ++i)
819 *i->Addr = i->Saved;
820 }
821 };
822}
823
824/// checkPlaceholderForOverload - Do any interesting placeholder-like
825/// preprocessing on the given expression.
826///
827/// \param unbridgedCasts a collection to which to add unbridged casts;
828/// without this, they will be immediately diagnosed as errors
829///
830/// Return true on unrecoverable error.
831static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
832 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall5acb0c92011-10-17 18:40:02 +0000833 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
834 // We can't handle overloaded expressions here because overload
835 // resolution might reasonably tweak them.
836 if (placeholder->getKind() == BuiltinType::Overload) return false;
837
838 // If the context potentially accepts unbridged ARC casts, strip
839 // the unbridged cast and add it to the collection for later restoration.
840 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
841 unbridgedCasts) {
842 unbridgedCasts->save(S, E);
843 return false;
844 }
845
846 // Go ahead and check everything else.
847 ExprResult result = S.CheckPlaceholderExpr(E);
848 if (result.isInvalid())
849 return true;
850
851 E = result.take();
852 return false;
853 }
854
855 // Nothing to do.
856 return false;
857}
858
859/// checkArgPlaceholdersForOverload - Check a set of call operands for
860/// placeholders.
Dmitri Gribenko9e00f122013-05-09 21:02:07 +0000861static bool checkArgPlaceholdersForOverload(Sema &S,
862 MultiExprArg Args,
John McCall5acb0c92011-10-17 18:40:02 +0000863 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9e00f122013-05-09 21:02:07 +0000864 for (unsigned i = 0, e = Args.size(); i != e; ++i)
865 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall5acb0c92011-10-17 18:40:02 +0000866 return true;
867
868 return false;
869}
870
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000871// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000872// overload of the declarations in Old. This routine returns false if
873// New and Old cannot be overloaded, e.g., if New has the same
874// signature as some function in Old (C++ 1.3.10) or if the Old
875// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000876// it does return false, MatchedDecl will point to the decl that New
877// cannot be overloaded with. This decl may be a UsingShadowDecl on
878// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000879//
880// Example: Given the following input:
881//
882// void f(int, float); // #1
883// void f(int, int); // #2
884// int f(int, int); // #3
885//
886// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000887// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000888//
John McCall51fa86f2009-12-02 08:47:38 +0000889// When we process #2, Old contains only the FunctionDecl for #1. By
890// comparing the parameter types, we see that #1 and #2 are overloaded
891// (since they have different signatures), so this routine returns
892// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000893//
John McCall51fa86f2009-12-02 08:47:38 +0000894// When we process #3, Old is an overload set containing #1 and #2. We
895// compare the signatures of #3 to #1 (they're overloaded, so we do
896// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
897// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000898// signature), IsOverload returns false and MatchedDecl will be set to
899// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000900//
901// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
902// into a class by a using declaration. The rules for whether to hide
903// shadow declarations ignore some properties which otherwise figure
904// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000905Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000906Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
907 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000908 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000909 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000910 NamedDecl *OldD = *I;
911
912 bool OldIsUsingDecl = false;
913 if (isa<UsingShadowDecl>(OldD)) {
914 OldIsUsingDecl = true;
915
916 // We can always introduce two using declarations into the same
917 // context, even if they have identical signatures.
918 if (NewIsUsingDecl) continue;
919
920 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
921 }
922
923 // If either declaration was introduced by a using declaration,
924 // we'll need to use slightly different rules for matching.
925 // Essentially, these rules are the normal rules, except that
926 // function templates hide function templates with different
927 // return types or template parameter lists.
928 bool UseMemberUsingDeclRules =
John McCall78037ac2013-04-03 21:19:47 +0000929 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
930 !New->getFriendObjectKind();
John McCallad00b772010-06-16 08:42:20 +0000931
John McCall51fa86f2009-12-02 08:47:38 +0000932 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000933 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
934 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
935 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
936 continue;
937 }
938
John McCall871b2e72009-12-09 03:35:25 +0000939 Match = *I;
940 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000941 }
John McCall51fa86f2009-12-02 08:47:38 +0000942 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000943 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
944 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
945 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
946 continue;
947 }
948
Rafael Espindola90cc3902013-04-15 12:49:13 +0000949 if (!shouldLinkPossiblyHiddenDecl(*I, New))
950 continue;
951
John McCall871b2e72009-12-09 03:35:25 +0000952 Match = *I;
953 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000954 }
John McCalld7945c62010-11-10 03:01:53 +0000955 } else if (isa<UsingDecl>(OldD)) {
John McCall9f54ad42009-12-10 09:41:52 +0000956 // We can overload with these, which can show up when doing
957 // redeclaration checks for UsingDecls.
958 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalld7945c62010-11-10 03:01:53 +0000959 } else if (isa<TagDecl>(OldD)) {
960 // We can always overload with tags by hiding them.
John McCall9f54ad42009-12-10 09:41:52 +0000961 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
962 // Optimistically assume that an unresolved using decl will
963 // overload; if it doesn't, we'll have to diagnose during
964 // template instantiation.
965 } else {
John McCall68263142009-11-18 22:49:29 +0000966 // (C++ 13p1):
967 // Only function declarations can be overloaded; object and type
968 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000969 Match = *I;
970 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000971 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000972 }
John McCall68263142009-11-18 22:49:29 +0000973
John McCall871b2e72009-12-09 03:35:25 +0000974 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000975}
976
Richard Smithaa4bc182013-06-30 09:48:50 +0000977bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
978 bool UseUsingDeclRules) {
979 // C++ [basic.start.main]p2: This function shall not be overloaded.
980 if (New->isMain())
Rafael Espindola78eeba82012-12-28 14:21:58 +0000981 return false;
Rafael Espindola7a525ac2013-01-12 01:47:40 +0000982
David Majnemere9f6f332013-09-16 22:44:20 +0000983 // MSVCRT user defined entry points cannot be overloaded.
984 if (New->isMSVCRTEntryPoint())
985 return false;
986
John McCall68263142009-11-18 22:49:29 +0000987 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
988 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
989
990 // C++ [temp.fct]p2:
991 // A function template can be overloaded with other function templates
992 // and with normal (non-template) functions.
993 if ((OldTemplate == 0) != (NewTemplate == 0))
994 return true;
995
996 // Is the function New an overload of the function Old?
Richard Smithaa4bc182013-06-30 09:48:50 +0000997 QualType OldQType = Context.getCanonicalType(Old->getType());
998 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall68263142009-11-18 22:49:29 +0000999
1000 // Compare the signatures (C++ 1.3.10) of the two functions to
1001 // determine whether they are overloads. If we find any mismatch
1002 // in the signature, they are overloads.
1003
1004 // If either of these functions is a K&R-style function (no
1005 // prototype), then we consider them to have matching signatures.
1006 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1007 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1008 return false;
1009
John McCallf4c73712011-01-19 06:33:43 +00001010 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
1011 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall68263142009-11-18 22:49:29 +00001012
1013 // The signature of a function includes the types of its
1014 // parameters (C++ 1.3.10), which includes the presence or absence
1015 // of the ellipsis; see C++ DR 357).
1016 if (OldQType != NewQType &&
1017 (OldType->getNumArgs() != NewType->getNumArgs() ||
1018 OldType->isVariadic() != NewType->isVariadic() ||
Richard Smithaa4bc182013-06-30 09:48:50 +00001019 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +00001020 return true;
1021
1022 // C++ [temp.over.link]p4:
1023 // The signature of a function template consists of its function
1024 // signature, its return type and its template parameter list. The names
1025 // of the template parameters are significant only for establishing the
1026 // relationship between the template parameters and the rest of the
1027 // signature.
1028 //
1029 // We check the return type and template parameter lists for function
1030 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +00001031 //
1032 // However, we don't consider either of these when deciding whether
1033 // a member introduced by a shadow declaration is hidden.
1034 if (!UseUsingDeclRules && NewTemplate &&
Richard Smithaa4bc182013-06-30 09:48:50 +00001035 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1036 OldTemplate->getTemplateParameters(),
1037 false, TPL_TemplateMatch) ||
John McCall68263142009-11-18 22:49:29 +00001038 OldType->getResultType() != NewType->getResultType()))
1039 return true;
1040
1041 // If the function is a class member, its signature includes the
Douglas Gregor57c9f4f2011-01-26 17:47:49 +00001042 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall68263142009-11-18 22:49:29 +00001043 //
1044 // As part of this, also check whether one of the member functions
1045 // is static, in which case they are not overloads (C++
1046 // 13.1p2). While not part of the definition of the signature,
1047 // this check is important to determine whether these functions
1048 // can be overloaded.
Richard Smith21c8fa82013-01-14 05:37:29 +00001049 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1050 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall68263142009-11-18 22:49:29 +00001051 if (OldMethod && NewMethod &&
Richard Smith21c8fa82013-01-14 05:37:29 +00001052 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1053 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1054 if (!UseUsingDeclRules &&
1055 (OldMethod->getRefQualifier() == RQ_None ||
1056 NewMethod->getRefQualifier() == RQ_None)) {
1057 // C++0x [over.load]p2:
1058 // - Member function declarations with the same name and the same
1059 // parameter-type-list as well as member function template
1060 // declarations with the same name, the same parameter-type-list, and
1061 // the same template parameter lists cannot be overloaded if any of
1062 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithaa4bc182013-06-30 09:48:50 +00001063 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith21c8fa82013-01-14 05:37:29 +00001064 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithaa4bc182013-06-30 09:48:50 +00001065 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith21c8fa82013-01-14 05:37:29 +00001066 }
1067 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +00001068 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001069
Richard Smith21c8fa82013-01-14 05:37:29 +00001070 // We may not have applied the implicit const for a constexpr member
1071 // function yet (because we haven't yet resolved whether this is a static
1072 // or non-static member function). Add it now, on the assumption that this
1073 // is a redeclaration of OldMethod.
1074 unsigned NewQuals = NewMethod->getTypeQualifiers();
Richard Smithaa4bc182013-06-30 09:48:50 +00001075 if (!getLangOpts().CPlusPlus1y && NewMethod->isConstexpr() &&
Richard Smithdb2fe732013-06-25 18:46:26 +00001076 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith21c8fa82013-01-14 05:37:29 +00001077 NewQuals |= Qualifiers::Const;
1078 if (OldMethod->getTypeQualifiers() != NewQuals)
1079 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +00001080 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001081
John McCall68263142009-11-18 22:49:29 +00001082 // The signatures match; this is not an overload.
1083 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001084}
1085
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00001086/// \brief Checks availability of the function depending on the current
1087/// function context. Inside an unavailable function, unavailability is ignored.
1088///
1089/// \returns true if \arg FD is unavailable and current context is inside
1090/// an available function, false otherwise.
1091bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1092 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1093}
1094
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001095/// \brief Tries a user-defined conversion from From to ToType.
1096///
1097/// Produces an implicit conversion sequence for when a standard conversion
1098/// is not an option. See TryImplicitConversion for more information.
1099static ImplicitConversionSequence
1100TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1101 bool SuppressUserConversions,
1102 bool AllowExplicit,
1103 bool InOverloadResolution,
1104 bool CStyle,
1105 bool AllowObjCWritebackConversion) {
1106 ImplicitConversionSequence ICS;
1107
1108 if (SuppressUserConversions) {
1109 // We're not in the case above, so there is no conversion that
1110 // we can perform.
1111 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1112 return ICS;
1113 }
1114
1115 // Attempt user-defined conversion.
1116 OverloadCandidateSet Conversions(From->getExprLoc());
1117 OverloadingResult UserDefResult
1118 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1119 AllowExplicit);
1120
1121 if (UserDefResult == OR_Success) {
1122 ICS.setUserDefined();
1123 // C++ [over.ics.user]p4:
1124 // A conversion of an expression of class type to the same class
1125 // type is given Exact Match rank, and a conversion of an
1126 // expression of class type to a base class of that type is
1127 // given Conversion rank, in spite of the fact that a copy
1128 // constructor (i.e., a user-defined conversion function) is
1129 // called for those cases.
1130 if (CXXConstructorDecl *Constructor
1131 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1132 QualType FromCanon
1133 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1134 QualType ToCanon
1135 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1136 if (Constructor->isCopyConstructor() &&
1137 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1138 // Turn this into a "standard" conversion sequence, so that it
1139 // gets ranked with standard conversion sequences.
1140 ICS.setStandard();
1141 ICS.Standard.setAsIdentityConversion();
1142 ICS.Standard.setFromType(From->getType());
1143 ICS.Standard.setAllToTypes(ToType);
1144 ICS.Standard.CopyConstructor = Constructor;
1145 if (ToCanon != FromCanon)
1146 ICS.Standard.Second = ICK_Derived_To_Base;
1147 }
1148 }
1149
1150 // C++ [over.best.ics]p4:
1151 // However, when considering the argument of a user-defined
1152 // conversion function that is a candidate by 13.3.1.3 when
1153 // invoked for the copying of the temporary in the second step
1154 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1155 // 13.3.1.6 in all cases, only standard conversion sequences and
1156 // ellipsis conversion sequences are allowed.
1157 if (SuppressUserConversions && ICS.isUserDefined()) {
1158 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1159 }
1160 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1161 ICS.setAmbiguous();
1162 ICS.Ambiguous.setFromType(From->getType());
1163 ICS.Ambiguous.setToType(ToType);
1164 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1165 Cand != Conversions.end(); ++Cand)
1166 if (Cand->Viable)
1167 ICS.Ambiguous.addConversion(Cand->Function);
1168 } else {
1169 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1170 }
1171
1172 return ICS;
1173}
1174
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001175/// TryImplicitConversion - Attempt to perform an implicit conversion
1176/// from the given expression (Expr) to the given type (ToType). This
1177/// function returns an implicit conversion sequence that can be used
1178/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001179///
1180/// void f(float f);
1181/// void g(int i) { f(i); }
1182///
1183/// this routine would produce an implicit conversion sequence to
1184/// describe the initialization of f from i, which will be a standard
1185/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1186/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1187//
1188/// Note that this routine only determines how the conversion can be
1189/// performed; it does not actually perform the conversion. As such,
1190/// it will not produce any diagnostics if no conversion is available,
1191/// but will instead return an implicit conversion sequence of kind
1192/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +00001193///
1194/// If @p SuppressUserConversions, then user-defined conversions are
1195/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001196/// If @p AllowExplicit, then explicit user-defined conversions are
1197/// permitted.
John McCallf85e1932011-06-15 23:02:42 +00001198///
1199/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1200/// writeback conversion, which allows __autoreleasing id* parameters to
1201/// be initialized with __strong id* or __weak id* arguments.
John McCall120d63c2010-08-24 20:38:10 +00001202static ImplicitConversionSequence
1203TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1204 bool SuppressUserConversions,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001205 bool AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001206 bool InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001207 bool CStyle,
1208 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001209 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +00001210 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001211 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall1d318332010-01-12 00:44:57 +00001212 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +00001213 return ICS;
1214 }
1215
David Blaikie4e4d0842012-03-11 07:00:24 +00001216 if (!S.getLangOpts().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +00001217 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +00001218 return ICS;
1219 }
1220
Douglas Gregor604eb652010-08-11 02:15:33 +00001221 // C++ [over.ics.user]p4:
1222 // A conversion of an expression of class type to the same class
1223 // type is given Exact Match rank, and a conversion of an
1224 // expression of class type to a base class of that type is
1225 // given Conversion rank, in spite of the fact that a copy/move
1226 // constructor (i.e., a user-defined conversion function) is
1227 // called for those cases.
1228 QualType FromType = From->getType();
1229 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00001230 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1231 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001232 ICS.setStandard();
1233 ICS.Standard.setAsIdentityConversion();
1234 ICS.Standard.setFromType(FromType);
1235 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001236
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001237 // We don't actually check at this point whether there is a valid
1238 // copy/move constructor, since overloading just assumes that it
1239 // exists. When we actually perform initialization, we'll find the
1240 // appropriate constructor to copy the returned object, if needed.
1241 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001242
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001243 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +00001244 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001245 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001246
Douglas Gregor604eb652010-08-11 02:15:33 +00001247 return ICS;
1248 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001249
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001250 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1251 AllowExplicit, InOverloadResolution, CStyle,
1252 AllowObjCWritebackConversion);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001253}
1254
John McCallf85e1932011-06-15 23:02:42 +00001255ImplicitConversionSequence
1256Sema::TryImplicitConversion(Expr *From, QualType ToType,
1257 bool SuppressUserConversions,
1258 bool AllowExplicit,
1259 bool InOverloadResolution,
1260 bool CStyle,
1261 bool AllowObjCWritebackConversion) {
1262 return clang::TryImplicitConversion(*this, From, ToType,
1263 SuppressUserConversions, AllowExplicit,
1264 InOverloadResolution, CStyle,
1265 AllowObjCWritebackConversion);
John McCall120d63c2010-08-24 20:38:10 +00001266}
1267
Douglas Gregor575c63a2010-04-16 22:27:05 +00001268/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley429bb272011-04-08 18:41:53 +00001269/// expression From to the type ToType. Returns the
Douglas Gregor575c63a2010-04-16 22:27:05 +00001270/// converted expression. Flavor is the kind of conversion we're
1271/// performing, used in the error message. If @p AllowExplicit,
1272/// explicit user-defined conversions are permitted.
John Wiegley429bb272011-04-08 18:41:53 +00001273ExprResult
1274Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001275 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregor575c63a2010-04-16 22:27:05 +00001276 ImplicitConversionSequence ICS;
Sebastian Redl091fffe2011-10-16 18:19:06 +00001277 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001278}
1279
John Wiegley429bb272011-04-08 18:41:53 +00001280ExprResult
1281Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor575c63a2010-04-16 22:27:05 +00001282 AssignmentAction Action, bool AllowExplicit,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001283 ImplicitConversionSequence& ICS) {
John McCall3c3b7f92011-10-25 17:37:35 +00001284 if (checkPlaceholderForOverload(*this, From))
1285 return ExprError();
1286
John McCallf85e1932011-06-15 23:02:42 +00001287 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1288 bool AllowObjCWritebackConversion
David Blaikie4e4d0842012-03-11 07:00:24 +00001289 = getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001290 (Action == AA_Passing || Action == AA_Sending);
John McCallf85e1932011-06-15 23:02:42 +00001291
John McCall120d63c2010-08-24 20:38:10 +00001292 ICS = clang::TryImplicitConversion(*this, From, ToType,
1293 /*SuppressUserConversions=*/false,
1294 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001295 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00001296 /*CStyle=*/false,
1297 AllowObjCWritebackConversion);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001298 return PerformImplicitConversion(From, ToType, ICS, Action);
1299}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001300
1301/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor43c79c22009-12-09 00:47:37 +00001302/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth18e04612011-06-18 01:19:03 +00001303bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1304 QualType &ResultTy) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001305 if (Context.hasSameUnqualifiedType(FromType, ToType))
1306 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001307
John McCall00ccbef2010-12-21 00:44:39 +00001308 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1309 // where F adds one of the following at most once:
1310 // - a pointer
1311 // - a member pointer
1312 // - a block pointer
1313 CanQualType CanTo = Context.getCanonicalType(ToType);
1314 CanQualType CanFrom = Context.getCanonicalType(FromType);
1315 Type::TypeClass TyClass = CanTo->getTypeClass();
1316 if (TyClass != CanFrom->getTypeClass()) return false;
1317 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1318 if (TyClass == Type::Pointer) {
1319 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1320 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1321 } else if (TyClass == Type::BlockPointer) {
1322 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1323 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1324 } else if (TyClass == Type::MemberPointer) {
1325 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1326 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1327 } else {
1328 return false;
1329 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001330
John McCall00ccbef2010-12-21 00:44:39 +00001331 TyClass = CanTo->getTypeClass();
1332 if (TyClass != CanFrom->getTypeClass()) return false;
1333 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1334 return false;
1335 }
1336
1337 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1338 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1339 if (!EInfo.getNoReturn()) return false;
1340
1341 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1342 assert(QualType(FromFn, 0).isCanonical());
1343 if (QualType(FromFn, 0) != CanTo) return false;
1344
1345 ResultTy = ToType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001346 return true;
1347}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001348
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001349/// \brief Determine whether the conversion from FromType to ToType is a valid
1350/// vector conversion.
1351///
1352/// \param ICK Will be set to the vector conversion kind, if this is a vector
1353/// conversion.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001354static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1355 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001356 // We need at least one of these types to be a vector type to have a vector
1357 // conversion.
1358 if (!ToType->isVectorType() && !FromType->isVectorType())
1359 return false;
1360
1361 // Identical types require no conversions.
1362 if (Context.hasSameUnqualifiedType(FromType, ToType))
1363 return false;
1364
1365 // There are no conversions between extended vector types, only identity.
1366 if (ToType->isExtVectorType()) {
1367 // There are no conversions between extended vector types other than the
1368 // identity conversion.
1369 if (FromType->isExtVectorType())
1370 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001371
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001372 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +00001373 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001374 ICK = ICK_Vector_Splat;
1375 return true;
1376 }
1377 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001378
1379 // We can perform the conversion between vector types in the following cases:
1380 // 1)vector types are equivalent AltiVec and GCC vector types
1381 // 2)lax vector conversions are permitted and the vector types are of the
1382 // same size
1383 if (ToType->isVectorType() && FromType->isVectorType()) {
1384 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
David Blaikie4e4d0842012-03-11 07:00:24 +00001385 (Context.getLangOpts().LaxVectorConversions &&
Chandler Carruthc45eb9c2010-08-08 05:02:51 +00001386 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +00001387 ICK = ICK_Vector_Conversion;
1388 return true;
1389 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001390 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001391
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001392 return false;
1393}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001394
Douglas Gregor7d000652012-04-12 20:48:09 +00001395static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1396 bool InOverloadResolution,
1397 StandardConversionSequence &SCS,
1398 bool CStyle);
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001399
Douglas Gregor60d62c22008-10-31 16:23:19 +00001400/// IsStandardConversion - Determines whether there is a standard
1401/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1402/// expression From to the type ToType. Standard conversion sequences
1403/// only consider non-class types; for conversions that involve class
1404/// types, use TryImplicitConversion. If a conversion exists, SCS will
1405/// contain the standard conversion sequence required to perform this
1406/// conversion and this routine will return true. Otherwise, this
1407/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +00001408static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1409 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001410 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +00001411 bool CStyle,
1412 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001413 QualType FromType = From->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001414
Douglas Gregor60d62c22008-10-31 16:23:19 +00001415 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001416 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +00001417 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +00001418 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +00001419 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +00001420 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001421
Douglas Gregorf9201e02009-02-11 23:02:49 +00001422 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +00001423 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +00001424 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001425 if (S.getLangOpts().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001426 return false;
1427
Mike Stump1eb44332009-09-09 15:08:12 +00001428 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001429 }
1430
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001431 // The first conversion can be an lvalue-to-rvalue conversion,
1432 // array-to-pointer conversion, or function-to-pointer conversion
1433 // (C++ 4p1).
1434
John McCall120d63c2010-08-24 20:38:10 +00001435 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001436 DeclAccessPair AccessPair;
1437 if (FunctionDecl *Fn
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001438 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall120d63c2010-08-24 20:38:10 +00001439 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001440 // We were able to resolve the address of the overloaded function,
1441 // so we can convert to the type of that function.
1442 FromType = Fn->getType();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001443
1444 // we can sometimes resolve &foo<int> regardless of ToType, so check
1445 // if the type matches (identity) or we are converting to bool
1446 if (!S.Context.hasSameUnqualifiedType(
1447 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1448 QualType resultTy;
1449 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth18e04612011-06-18 01:19:03 +00001450 if (!S.IsNoReturnConversion(FromType,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001451 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1452 // otherwise, only a boolean conversion is standard
1453 if (!ToType->isBooleanType())
1454 return false;
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001455 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001456
Chandler Carruth90434232011-03-29 08:08:18 +00001457 // Check if the "from" expression is taking the address of an overloaded
1458 // function and recompute the FromType accordingly. Take advantage of the
1459 // fact that non-static member functions *must* have such an address-of
1460 // expression.
1461 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1462 if (Method && !Method->isStatic()) {
1463 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1464 "Non-unary operator on non-static member address");
1465 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1466 == UO_AddrOf &&
1467 "Non-address-of operator on non-static member address");
1468 const Type *ClassType
1469 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1470 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruthfc5c8fc2011-03-29 18:38:10 +00001471 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1472 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1473 UO_AddrOf &&
Chandler Carruth90434232011-03-29 08:08:18 +00001474 "Non-address-of operator for overloaded function expression");
1475 FromType = S.Context.getPointerType(FromType);
1476 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001477
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001478 // Check that we've computed the proper type after overload resolution.
Chandler Carruth90434232011-03-29 08:08:18 +00001479 assert(S.Context.hasSameType(
1480 FromType,
1481 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001482 } else {
1483 return false;
1484 }
Anders Carlsson2bd62502010-11-04 05:28:09 +00001485 }
John McCall21480112011-08-30 00:57:29 +00001486 // Lvalue-to-rvalue conversion (C++11 4.1):
1487 // A glvalue (3.10) of a non-function, non-array type T can
1488 // be converted to a prvalue.
1489 bool argIsLValue = From->isGLValue();
John McCall7eb0a9e2010-11-24 05:12:34 +00001490 if (argIsLValue &&
Douglas Gregor904eed32008-11-10 20:40:00 +00001491 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +00001492 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001493 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001494
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001495 // C11 6.3.2.1p2:
1496 // ... if the lvalue has atomic type, the value has the non-atomic version
1497 // of the type of the lvalue ...
1498 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1499 FromType = Atomic->getValueType();
1500
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001501 // If T is a non-class type, the type of the rvalue is the
1502 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001503 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1504 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001505 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001506 } else if (FromType->isArrayType()) {
1507 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001508 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001509
1510 // An lvalue or rvalue of type "array of N T" or "array of unknown
1511 // bound of T" can be converted to an rvalue of type "pointer to
1512 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001513 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001514
John McCall120d63c2010-08-24 20:38:10 +00001515 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001516 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001517 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001518
1519 // For the purpose of ranking in overload resolution
1520 // (13.3.3.1.1), this conversion is considered an
1521 // array-to-pointer conversion followed by a qualification
1522 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001523 SCS.Second = ICK_Identity;
1524 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001525 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregorad323a82010-01-27 03:51:04 +00001526 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001527 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001528 }
John McCall7eb0a9e2010-11-24 05:12:34 +00001529 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001530 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001531 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001532
1533 // An lvalue of function type T can be converted to an rvalue of
1534 // type "pointer to T." The result is a pointer to the
1535 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001536 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001537 } else {
1538 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001539 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001540 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001541 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001542
1543 // The second conversion can be an integral promotion, floating
1544 // point promotion, integral conversion, floating point conversion,
1545 // floating-integral conversion, pointer conversion,
1546 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001547 // For overloading in C, this can also be a "compatible-type"
1548 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001549 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001550 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001551 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001552 // The unqualified versions of the types are the same: there's no
1553 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001554 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001555 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001556 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001557 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001558 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001559 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001560 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001561 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001562 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001563 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001564 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001565 SCS.Second = ICK_Complex_Promotion;
1566 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001567 } else if (ToType->isBooleanType() &&
1568 (FromType->isArithmeticType() ||
1569 FromType->isAnyPointerType() ||
1570 FromType->isBlockPointerType() ||
1571 FromType->isMemberPointerType() ||
1572 FromType->isNullPtrType())) {
1573 // Boolean conversions (C++ 4.12).
1574 SCS.Second = ICK_Boolean_Conversion;
1575 FromType = S.Context.BoolTy;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001576 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001577 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001578 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001579 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001580 FromType = ToType.getUnqualifiedType();
Richard Smith42860f12013-05-10 20:29:50 +00001581 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001582 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001583 SCS.Second = ICK_Complex_Conversion;
1584 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001585 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1586 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001587 // Complex-real conversions (C99 6.3.1.7)
1588 SCS.Second = ICK_Complex_Real;
1589 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001590 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001591 // Floating point conversions (C++ 4.8).
1592 SCS.Second = ICK_Floating_Conversion;
1593 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001594 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001595 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001596 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001597 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001598 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001599 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001600 FromType = ToType.getUnqualifiedType();
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001601 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCallf85e1932011-06-15 23:02:42 +00001602 SCS.Second = ICK_Block_Pointer_Conversion;
1603 } else if (AllowObjCWritebackConversion &&
1604 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1605 SCS.Second = ICK_Writeback_Conversion;
John McCall120d63c2010-08-24 20:38:10 +00001606 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1607 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001608 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001609 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001610 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001611 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001612 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall120d63c2010-08-24 20:38:10 +00001613 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001614 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001615 SCS.Second = ICK_Pointer_Member;
John McCall120d63c2010-08-24 20:38:10 +00001616 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001617 SCS.Second = SecondICK;
1618 FromType = ToType.getUnqualifiedType();
David Blaikie4e4d0842012-03-11 07:00:24 +00001619 } else if (!S.getLangOpts().CPlusPlus &&
John McCall120d63c2010-08-24 20:38:10 +00001620 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001621 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001622 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001623 FromType = ToType.getUnqualifiedType();
Chandler Carruth18e04612011-06-18 01:19:03 +00001624 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001625 // Treat a conversion that strips "noreturn" as an identity conversion.
1626 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001627 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1628 InOverloadResolution,
1629 SCS, CStyle)) {
1630 SCS.Second = ICK_TransparentUnionConversion;
1631 FromType = ToType;
Douglas Gregor7d000652012-04-12 20:48:09 +00001632 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1633 CStyle)) {
1634 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001635 // appropriately.
1636 return true;
Guy Benyei6959acd2013-02-07 16:05:33 +00001637 } else if (ToType->isEventT() &&
1638 From->isIntegerConstantExpr(S.getASTContext()) &&
1639 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1640 SCS.Second = ICK_Zero_Event_Conversion;
1641 FromType = ToType;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001642 } else {
1643 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001644 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001645 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001646 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001647
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001648 QualType CanonFrom;
1649 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001650 // The third conversion can be a qualification conversion (C++ 4p1).
John McCallf85e1932011-06-15 23:02:42 +00001651 bool ObjCLifetimeConversion;
1652 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1653 ObjCLifetimeConversion)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001654 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001655 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001656 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001657 CanonFrom = S.Context.getCanonicalType(FromType);
1658 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001659 } else {
1660 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001661 SCS.Third = ICK_Identity;
1662
Mike Stump1eb44332009-09-09 15:08:12 +00001663 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001664 // [...] Any difference in top-level cv-qualification is
1665 // subsumed by the initialization itself and does not constitute
1666 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001667 CanonFrom = S.Context.getCanonicalType(FromType);
1668 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001669 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregora4923eb2009-11-16 21:35:15 +00001670 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault5509f372013-02-26 21:15:54 +00001671 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001672 FromType = ToType;
1673 CanonFrom = CanonTo;
1674 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001675 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001676 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001677
1678 // If we have not converted the argument type to the parameter type,
1679 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001680 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001681 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001682
Douglas Gregor60d62c22008-10-31 16:23:19 +00001683 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001684}
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001685
1686static bool
1687IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1688 QualType &ToType,
1689 bool InOverloadResolution,
1690 StandardConversionSequence &SCS,
1691 bool CStyle) {
1692
1693 const RecordType *UT = ToType->getAsUnionType();
1694 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1695 return false;
1696 // The field to initialize within the transparent union.
1697 RecordDecl *UD = UT->getDecl();
1698 // It's compatible if the expression matches any of the fields.
1699 for (RecordDecl::field_iterator it = UD->field_begin(),
1700 itend = UD->field_end();
1701 it != itend; ++it) {
John McCallf85e1932011-06-15 23:02:42 +00001702 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1703 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001704 ToType = it->getType();
1705 return true;
1706 }
1707 }
1708 return false;
1709}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001710
1711/// IsIntegralPromotion - Determines whether the conversion from the
1712/// expression From (whose potentially-adjusted type is FromType) to
1713/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1714/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001715bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001716 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001717 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001718 if (!To) {
1719 return false;
1720 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001721
1722 // An rvalue of type char, signed char, unsigned char, short int, or
1723 // unsigned short int can be converted to an rvalue of type int if
1724 // int can represent all the values of the source type; otherwise,
1725 // the source rvalue can be converted to an rvalue of type unsigned
1726 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001727 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1728 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001729 if (// We can promote any signed, promotable integer type to an int
1730 (FromType->isSignedIntegerType() ||
1731 // We can promote any unsigned integer type whose size is
1732 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001733 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001734 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001735 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001736 }
1737
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001738 return To->getKind() == BuiltinType::UInt;
1739 }
1740
Richard Smithe7ff9192012-09-13 21:18:54 +00001741 // C++11 [conv.prom]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001742 // A prvalue of an unscoped enumeration type whose underlying type is not
1743 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1744 // following types that can represent all the values of the enumeration
1745 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1746 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001747 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001748 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001749 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001750 // with lowest integer conversion rank (4.13) greater than the rank of long
1751 // long in which all the values of the enumeration can be represented. If
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001752 // there are two such extended types, the signed one is chosen.
Richard Smithe7ff9192012-09-13 21:18:54 +00001753 // C++11 [conv.prom]p4:
1754 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1755 // can be converted to a prvalue of its underlying type. Moreover, if
1756 // integral promotion can be applied to its underlying type, a prvalue of an
1757 // unscoped enumeration type whose underlying type is fixed can also be
1758 // converted to a prvalue of the promoted underlying type.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001759 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1760 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1761 // provided for a scoped enumeration.
1762 if (FromEnumType->getDecl()->isScoped())
1763 return false;
1764
Richard Smithe7ff9192012-09-13 21:18:54 +00001765 // We can perform an integral promotion to the underlying type of the enum,
1766 // even if that's not the promoted type.
1767 if (FromEnumType->getDecl()->isFixed()) {
1768 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1769 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1770 IsIntegralPromotion(From, Underlying, ToType);
1771 }
1772
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001773 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001774 if (ToType->isIntegerType() &&
Douglas Gregord10099e2012-05-04 16:32:21 +00001775 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall842aef82009-12-09 09:09:27 +00001776 return Context.hasSameUnqualifiedType(ToType,
1777 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001778 }
John McCall842aef82009-12-09 09:09:27 +00001779
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001780 // C++0x [conv.prom]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001781 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1782 // to an rvalue a prvalue of the first of the following types that can
1783 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001784 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001785 // If none of the types in that list can represent all the values of its
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001786 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001787 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001788 // type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001789 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001790 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001791 // Determine whether the type we're converting from is signed or
1792 // unsigned.
David Majnemer0ad92312011-07-22 21:09:04 +00001793 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001794 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001795
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001796 // The types we'll try to promote to, in the appropriate
1797 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001798 QualType PromoteTypes[6] = {
1799 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001800 Context.LongTy, Context.UnsignedLongTy ,
1801 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001802 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001803 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001804 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1805 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001806 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001807 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1808 // We found the type that we can promote to. If this is the
1809 // type we wanted, we have a promotion. Otherwise, no
1810 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001811 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001812 }
1813 }
1814 }
1815
1816 // An rvalue for an integral bit-field (9.6) can be converted to an
1817 // rvalue of type int if int can represent all the values of the
1818 // bit-field; otherwise, it can be converted to unsigned int if
1819 // unsigned int can represent all the values of the bit-field. If
1820 // the bit-field is larger yet, no integral promotion applies to
1821 // it. If the bit-field has an enumerated type, it is treated as any
1822 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001823 // FIXME: We should delay checking of bit-fields until we actually perform the
1824 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001825 using llvm::APSInt;
1826 if (From)
John McCall993f43f2013-05-06 21:39:12 +00001827 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001828 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001829 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001830 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1831 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1832 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001833
Douglas Gregor86f19402008-12-20 23:49:58 +00001834 // Are we promoting to an int from a bitfield that fits in an int?
1835 if (BitWidth < ToSize ||
1836 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1837 return To->getKind() == BuiltinType::Int;
1838 }
Mike Stump1eb44332009-09-09 15:08:12 +00001839
Douglas Gregor86f19402008-12-20 23:49:58 +00001840 // Are we promoting to an unsigned int from an unsigned bitfield
1841 // that fits into an unsigned int?
1842 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1843 return To->getKind() == BuiltinType::UInt;
1844 }
Mike Stump1eb44332009-09-09 15:08:12 +00001845
Douglas Gregor86f19402008-12-20 23:49:58 +00001846 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001847 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001848 }
Mike Stump1eb44332009-09-09 15:08:12 +00001849
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001850 // An rvalue of type bool can be converted to an rvalue of type int,
1851 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001852 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001853 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001854 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001855
1856 return false;
1857}
1858
1859/// IsFloatingPointPromotion - Determines whether the conversion from
1860/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1861/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001862bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001863 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1864 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001865 /// An rvalue of type float can be converted to an rvalue of type
1866 /// double. (C++ 4.6p1).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001867 if (FromBuiltin->getKind() == BuiltinType::Float &&
1868 ToBuiltin->getKind() == BuiltinType::Double)
1869 return true;
1870
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001871 // C99 6.3.1.5p1:
1872 // When a float is promoted to double or long double, or a
1873 // double is promoted to long double [...].
David Blaikie4e4d0842012-03-11 07:00:24 +00001874 if (!getLangOpts().CPlusPlus &&
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001875 (FromBuiltin->getKind() == BuiltinType::Float ||
1876 FromBuiltin->getKind() == BuiltinType::Double) &&
1877 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1878 return true;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001879
1880 // Half can be promoted to float.
Joey Gouly19dbb202013-01-23 11:56:20 +00001881 if (!getLangOpts().NativeHalfType &&
1882 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001883 ToBuiltin->getKind() == BuiltinType::Float)
1884 return true;
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001885 }
1886
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001887 return false;
1888}
1889
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001890/// \brief Determine if a conversion is a complex promotion.
1891///
1892/// A complex promotion is defined as a complex -> complex conversion
1893/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001894/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001895bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001896 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001897 if (!FromComplex)
1898 return false;
1899
John McCall183700f2009-09-21 23:43:11 +00001900 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001901 if (!ToComplex)
1902 return false;
1903
1904 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001905 ToComplex->getElementType()) ||
1906 IsIntegralPromotion(0, FromComplex->getElementType(),
1907 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001908}
1909
Douglas Gregorcb7de522008-11-26 23:31:11 +00001910/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1911/// the pointer type FromPtr to a pointer to type ToPointee, with the
1912/// same type qualifiers as FromPtr has on its pointee type. ToType,
1913/// if non-empty, will be a pointer to ToType that may or may not have
1914/// the right set of qualifiers on its pointee.
John McCallf85e1932011-06-15 23:02:42 +00001915///
Mike Stump1eb44332009-09-09 15:08:12 +00001916static QualType
Douglas Gregorda80f742010-12-01 21:43:58 +00001917BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001918 QualType ToPointee, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00001919 ASTContext &Context,
1920 bool StripObjCLifetime = false) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001921 assert((FromPtr->getTypeClass() == Type::Pointer ||
1922 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1923 "Invalid similarly-qualified pointer type");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001924
John McCallf85e1932011-06-15 23:02:42 +00001925 /// Conversions to 'id' subsume cv-qualifier conversions.
1926 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregor143c7ac2010-12-06 22:09:19 +00001927 return ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001928
1929 QualType CanonFromPointee
Douglas Gregorda80f742010-12-01 21:43:58 +00001930 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregorcb7de522008-11-26 23:31:11 +00001931 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001932 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001933
John McCallf85e1932011-06-15 23:02:42 +00001934 if (StripObjCLifetime)
1935 Quals.removeObjCLifetime();
1936
Mike Stump1eb44332009-09-09 15:08:12 +00001937 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001938 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001939 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001940 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001941 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001942
1943 // Build a pointer to ToPointee. It has the right qualifiers
1944 // already.
Douglas Gregorda80f742010-12-01 21:43:58 +00001945 if (isa<ObjCObjectPointerType>(ToType))
1946 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregorcb7de522008-11-26 23:31:11 +00001947 return Context.getPointerType(ToPointee);
1948 }
1949
1950 // Just build a canonical type that has the right qualifiers.
Douglas Gregorda80f742010-12-01 21:43:58 +00001951 QualType QualifiedCanonToPointee
1952 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001953
Douglas Gregorda80f742010-12-01 21:43:58 +00001954 if (isa<ObjCObjectPointerType>(ToType))
1955 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1956 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001957}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001958
Mike Stump1eb44332009-09-09 15:08:12 +00001959static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001960 bool InOverloadResolution,
1961 ASTContext &Context) {
1962 // Handle value-dependent integral null pointer constants correctly.
1963 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1964 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001965 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001966 return !InOverloadResolution;
1967
Douglas Gregorce940492009-09-25 04:25:58 +00001968 return Expr->isNullPointerConstant(Context,
1969 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1970 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001971}
Mike Stump1eb44332009-09-09 15:08:12 +00001972
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001973/// IsPointerConversion - Determines whether the conversion of the
1974/// expression From, which has the (possibly adjusted) type FromType,
1975/// can be converted to the type ToType via a pointer conversion (C++
1976/// 4.10). If so, returns true and places the converted type (that
1977/// might differ from ToType in its cv-qualifiers at some level) into
1978/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001979///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001980/// This routine also supports conversions to and from block pointers
1981/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1982/// pointers to interfaces. FIXME: Once we've determined the
1983/// appropriate overloading rules for Objective-C, we may want to
1984/// split the Objective-C checks into a different routine; however,
1985/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001986/// conversions, so for now they live here. IncompatibleObjC will be
1987/// set if the conversion is an allowed Objective-C conversion that
1988/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001989bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001990 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001991 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001992 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001993 IncompatibleObjC = false;
Chandler Carruth6df868e2010-12-12 08:17:55 +00001994 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1995 IncompatibleObjC))
Douglas Gregorc7887512008-12-19 19:13:09 +00001996 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001997
Mike Stump1eb44332009-09-09 15:08:12 +00001998 // Conversion from a null pointer constant to any Objective-C pointer type.
1999 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002000 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00002001 ConvertedType = ToType;
2002 return true;
2003 }
2004
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002005 // Blocks: Block pointers can be converted to void*.
2006 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002007 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002008 ConvertedType = ToType;
2009 return true;
2010 }
2011 // Blocks: A null pointer constant can be converted to a block
2012 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00002013 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002014 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002015 ConvertedType = ToType;
2016 return true;
2017 }
2018
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002019 // If the left-hand-side is nullptr_t, the right side can be a null
2020 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00002021 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002022 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002023 ConvertedType = ToType;
2024 return true;
2025 }
2026
Ted Kremenek6217b802009-07-29 21:53:49 +00002027 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002028 if (!ToTypePtr)
2029 return false;
2030
2031 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002032 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002033 ConvertedType = ToType;
2034 return true;
2035 }
Sebastian Redl07779722008-10-31 14:43:28 +00002036
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002037 // Beyond this point, both types need to be pointers
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002038 // , including objective-c pointers.
2039 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002040 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002041 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002042 ConvertedType = BuildSimilarlyQualifiedPointerType(
2043 FromType->getAs<ObjCObjectPointerType>(),
2044 ToPointeeType,
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002045 ToType, Context);
2046 return true;
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002047 }
Ted Kremenek6217b802009-07-29 21:53:49 +00002048 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002049 if (!FromTypePtr)
2050 return false;
2051
2052 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002053
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002054 // If the unqualified pointee types are the same, this can't be a
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00002055 // pointer conversion, so don't do all of the work below.
2056 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2057 return false;
2058
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002059 // An rvalue of type "pointer to cv T," where T is an object type,
2060 // can be converted to an rvalue of type "pointer to cv void" (C++
2061 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00002062 if (FromPointeeType->isIncompleteOrObjectType() &&
2063 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002064 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002065 ToPointeeType,
John McCallf85e1932011-06-15 23:02:42 +00002066 ToType, Context,
2067 /*StripObjCLifetime=*/true);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002068 return true;
2069 }
2070
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002071 // MSVC allows implicit function to void* type conversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002072 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002073 ToPointeeType->isVoidType()) {
2074 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2075 ToPointeeType,
2076 ToType, Context);
2077 return true;
2078 }
2079
Douglas Gregorf9201e02009-02-11 23:02:49 +00002080 // When we're overloading in C, we allow a special kind of pointer
2081 // conversion for compatible-but-not-identical pointee types.
David Blaikie4e4d0842012-03-11 07:00:24 +00002082 if (!getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002083 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002084 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00002085 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00002086 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00002087 return true;
2088 }
2089
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002090 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00002091 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002092 // An rvalue of type "pointer to cv D," where D is a class type,
2093 // can be converted to an rvalue of type "pointer to cv B," where
2094 // B is a base class (clause 10) of D. If B is an inaccessible
2095 // (clause 11) or ambiguous (10.2) base class of D, a program that
2096 // necessitates this conversion is ill-formed. The result of the
2097 // conversion is a pointer to the base class sub-object of the
2098 // derived class object. The null pointer value is converted to
2099 // the null pointer value of the destination type.
2100 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002101 // Note that we do not check for ambiguity or inaccessibility
2102 // here. That is handled by CheckPointerConversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002103 if (getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002104 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00002105 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002106 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00002107 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002108 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002109 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002110 ToType, Context);
2111 return true;
2112 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002113
Fariborz Jahanian5da3c082011-04-14 20:33:36 +00002114 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2115 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2116 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2117 ToPointeeType,
2118 ToType, Context);
2119 return true;
2120 }
2121
Douglas Gregorc7887512008-12-19 19:13:09 +00002122 return false;
2123}
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002124
2125/// \brief Adopt the given qualifiers for the given type.
2126static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2127 Qualifiers TQs = T.getQualifiers();
2128
2129 // Check whether qualifiers already match.
2130 if (TQs == Qs)
2131 return T;
2132
2133 if (Qs.compatiblyIncludes(TQs))
2134 return Context.getQualifiedType(T, Qs);
2135
2136 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2137}
Douglas Gregorc7887512008-12-19 19:13:09 +00002138
2139/// isObjCPointerConversion - Determines whether this is an
2140/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2141/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00002142bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00002143 QualType& ConvertedType,
2144 bool &IncompatibleObjC) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002145 if (!getLangOpts().ObjC1)
Douglas Gregorc7887512008-12-19 19:13:09 +00002146 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002147
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002148 // The set of qualifiers on the type we're converting from.
2149 Qualifiers FromQualifiers = FromType.getQualifiers();
2150
Steve Naroff14108da2009-07-10 23:34:53 +00002151 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth6df868e2010-12-12 08:17:55 +00002152 const ObjCObjectPointerType* ToObjCPtr =
2153 ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002154 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00002155 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002156
Steve Naroff14108da2009-07-10 23:34:53 +00002157 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002158 // If the pointee types are the same (ignoring qualifications),
2159 // then this is not a pointer conversion.
2160 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2161 FromObjCPtr->getPointeeType()))
2162 return false;
2163
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002164 // Check for compatible
Steve Naroffde2e22d2009-07-15 18:40:39 +00002165 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00002166 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00002167 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002168 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002169 return true;
2170 }
2171 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00002172 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00002173 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00002174 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00002175 /*compare=*/false)) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002176 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002177 return true;
2178 }
2179 // Objective C++: We're able to convert from a pointer to an
2180 // interface to a pointer to a different interface.
2181 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002182 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2183 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002184 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002185 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2186 FromObjCPtr->getPointeeType()))
2187 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002188 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002189 ToObjCPtr->getPointeeType(),
2190 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002191 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002192 return true;
2193 }
2194
2195 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2196 // Okay: this is some kind of implicit downcast of Objective-C
2197 // interfaces, which is permitted. However, we're going to
2198 // complain about it.
2199 IncompatibleObjC = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002200 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002201 ToObjCPtr->getPointeeType(),
2202 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002203 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002204 return true;
2205 }
Mike Stump1eb44332009-09-09 15:08:12 +00002206 }
Steve Naroff14108da2009-07-10 23:34:53 +00002207 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002208 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002209 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002210 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002211 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002212 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00002213 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002214 // to a block pointer type.
2215 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002216 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002217 return true;
2218 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002219 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002220 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002221 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002222 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002223 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00002224 // pointer to any object.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002225 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002226 return true;
2227 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002228 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002229 return false;
2230
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002231 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002232 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002233 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth6df868e2010-12-12 08:17:55 +00002234 else if (const BlockPointerType *FromBlockPtr =
2235 FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002236 FromPointeeType = FromBlockPtr->getPointeeType();
2237 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002238 return false;
2239
Douglas Gregorc7887512008-12-19 19:13:09 +00002240 // If we have pointers to pointers, recursively check whether this
2241 // is an Objective-C conversion.
2242 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2243 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2244 IncompatibleObjC)) {
2245 // We always complain about this conversion.
2246 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00002247 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002248 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002249 return true;
2250 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002251 // Allow conversion of pointee being objective-c pointer to another one;
2252 // as in I* to id.
2253 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2254 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2255 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2256 IncompatibleObjC)) {
John McCallf85e1932011-06-15 23:02:42 +00002257
Douglas Gregorda80f742010-12-01 21:43:58 +00002258 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002259 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002260 return true;
2261 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002262
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002263 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00002264 // differences in the argument and result types are in Objective-C
2265 // pointer conversions. If so, we permit the conversion (but
2266 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00002267 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00002268 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00002269 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00002270 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002271 if (FromFunctionType && ToFunctionType) {
2272 // If the function types are exactly the same, this isn't an
2273 // Objective-C pointer conversion.
2274 if (Context.getCanonicalType(FromPointeeType)
2275 == Context.getCanonicalType(ToPointeeType))
2276 return false;
2277
2278 // Perform the quick checks that will tell us whether these
2279 // function types are obviously different.
2280 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2281 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2282 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2283 return false;
2284
2285 bool HasObjCConversion = false;
2286 if (Context.getCanonicalType(FromFunctionType->getResultType())
2287 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2288 // Okay, the types match exactly. Nothing to do.
2289 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2290 ToFunctionType->getResultType(),
2291 ConvertedType, IncompatibleObjC)) {
2292 // Okay, we have an Objective-C pointer conversion.
2293 HasObjCConversion = true;
2294 } else {
2295 // Function types are too different. Abort.
2296 return false;
2297 }
Mike Stump1eb44332009-09-09 15:08:12 +00002298
Douglas Gregorc7887512008-12-19 19:13:09 +00002299 // Check argument types.
2300 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2301 ArgIdx != NumArgs; ++ArgIdx) {
2302 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2303 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2304 if (Context.getCanonicalType(FromArgType)
2305 == Context.getCanonicalType(ToArgType)) {
2306 // Okay, the types match exactly. Nothing to do.
2307 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2308 ConvertedType, IncompatibleObjC)) {
2309 // Okay, we have an Objective-C pointer conversion.
2310 HasObjCConversion = true;
2311 } else {
2312 // Argument types are too different. Abort.
2313 return false;
2314 }
2315 }
2316
2317 if (HasObjCConversion) {
2318 // We had an Objective-C conversion. Allow this pointer
2319 // conversion, but complain about it.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002320 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002321 IncompatibleObjC = true;
2322 return true;
2323 }
2324 }
2325
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002326 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002327}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002328
John McCallf85e1932011-06-15 23:02:42 +00002329/// \brief Determine whether this is an Objective-C writeback conversion,
2330/// used for parameter passing when performing automatic reference counting.
2331///
2332/// \param FromType The type we're converting form.
2333///
2334/// \param ToType The type we're converting to.
2335///
2336/// \param ConvertedType The type that will be produced after applying
2337/// this conversion.
2338bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2339 QualType &ConvertedType) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002340 if (!getLangOpts().ObjCAutoRefCount ||
John McCallf85e1932011-06-15 23:02:42 +00002341 Context.hasSameUnqualifiedType(FromType, ToType))
2342 return false;
2343
2344 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2345 QualType ToPointee;
2346 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2347 ToPointee = ToPointer->getPointeeType();
2348 else
2349 return false;
2350
2351 Qualifiers ToQuals = ToPointee.getQualifiers();
2352 if (!ToPointee->isObjCLifetimeType() ||
2353 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall200fa532012-02-08 00:46:36 +00002354 !ToQuals.withoutObjCLifetime().empty())
John McCallf85e1932011-06-15 23:02:42 +00002355 return false;
2356
2357 // Argument must be a pointer to __strong to __weak.
2358 QualType FromPointee;
2359 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2360 FromPointee = FromPointer->getPointeeType();
2361 else
2362 return false;
2363
2364 Qualifiers FromQuals = FromPointee.getQualifiers();
2365 if (!FromPointee->isObjCLifetimeType() ||
2366 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2367 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2368 return false;
2369
2370 // Make sure that we have compatible qualifiers.
2371 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2372 if (!ToQuals.compatiblyIncludes(FromQuals))
2373 return false;
2374
2375 // Remove qualifiers from the pointee type we're converting from; they
2376 // aren't used in the compatibility check belong, and we'll be adding back
2377 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2378 FromPointee = FromPointee.getUnqualifiedType();
2379
2380 // The unqualified form of the pointee types must be compatible.
2381 ToPointee = ToPointee.getUnqualifiedType();
2382 bool IncompatibleObjC;
2383 if (Context.typesAreCompatible(FromPointee, ToPointee))
2384 FromPointee = ToPointee;
2385 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2386 IncompatibleObjC))
2387 return false;
2388
2389 /// \brief Construct the type we're converting to, which is a pointer to
2390 /// __autoreleasing pointee.
2391 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2392 ConvertedType = Context.getPointerType(FromPointee);
2393 return true;
2394}
2395
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002396bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2397 QualType& ConvertedType) {
2398 QualType ToPointeeType;
2399 if (const BlockPointerType *ToBlockPtr =
2400 ToType->getAs<BlockPointerType>())
2401 ToPointeeType = ToBlockPtr->getPointeeType();
2402 else
2403 return false;
2404
2405 QualType FromPointeeType;
2406 if (const BlockPointerType *FromBlockPtr =
2407 FromType->getAs<BlockPointerType>())
2408 FromPointeeType = FromBlockPtr->getPointeeType();
2409 else
2410 return false;
2411 // We have pointer to blocks, check whether the only
2412 // differences in the argument and result types are in Objective-C
2413 // pointer conversions. If so, we permit the conversion.
2414
2415 const FunctionProtoType *FromFunctionType
2416 = FromPointeeType->getAs<FunctionProtoType>();
2417 const FunctionProtoType *ToFunctionType
2418 = ToPointeeType->getAs<FunctionProtoType>();
2419
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002420 if (!FromFunctionType || !ToFunctionType)
2421 return false;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002422
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002423 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002424 return true;
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002425
2426 // Perform the quick checks that will tell us whether these
2427 // function types are obviously different.
2428 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2429 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2430 return false;
2431
2432 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2433 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2434 if (FromEInfo != ToEInfo)
2435 return false;
2436
2437 bool IncompatibleObjC = false;
Fariborz Jahanian462dae52011-02-13 20:11:42 +00002438 if (Context.hasSameType(FromFunctionType->getResultType(),
2439 ToFunctionType->getResultType())) {
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002440 // Okay, the types match exactly. Nothing to do.
2441 } else {
2442 QualType RHS = FromFunctionType->getResultType();
2443 QualType LHS = ToFunctionType->getResultType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002444 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002445 !RHS.hasQualifiers() && LHS.hasQualifiers())
2446 LHS = LHS.getUnqualifiedType();
2447
2448 if (Context.hasSameType(RHS,LHS)) {
2449 // OK exact match.
2450 } else if (isObjCPointerConversion(RHS, LHS,
2451 ConvertedType, IncompatibleObjC)) {
2452 if (IncompatibleObjC)
2453 return false;
2454 // Okay, we have an Objective-C pointer conversion.
2455 }
2456 else
2457 return false;
2458 }
2459
2460 // Check argument types.
2461 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2462 ArgIdx != NumArgs; ++ArgIdx) {
2463 IncompatibleObjC = false;
2464 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2465 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2466 if (Context.hasSameType(FromArgType, ToArgType)) {
2467 // Okay, the types match exactly. Nothing to do.
2468 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2469 ConvertedType, IncompatibleObjC)) {
2470 if (IncompatibleObjC)
2471 return false;
2472 // Okay, we have an Objective-C pointer conversion.
2473 } else
2474 // Argument types are too different. Abort.
2475 return false;
2476 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00002477 if (LangOpts.ObjCAutoRefCount &&
2478 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2479 ToFunctionType))
2480 return false;
Fariborz Jahanianf9d95272011-09-28 20:22:05 +00002481
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002482 ConvertedType = ToType;
2483 return true;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002484}
2485
Richard Trieu6efd4c52011-11-23 22:32:32 +00002486enum {
2487 ft_default,
2488 ft_different_class,
2489 ft_parameter_arity,
2490 ft_parameter_mismatch,
2491 ft_return_type,
2492 ft_qualifer_mismatch
2493};
2494
2495/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2496/// function types. Catches different number of parameter, mismatch in
2497/// parameter types, and different return types.
2498void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2499 QualType FromType, QualType ToType) {
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002500 // If either type is not valid, include no extra info.
2501 if (FromType.isNull() || ToType.isNull()) {
2502 PDiag << ft_default;
2503 return;
2504 }
2505
Richard Trieu6efd4c52011-11-23 22:32:32 +00002506 // Get the function type from the pointers.
2507 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2508 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2509 *ToMember = ToType->getAs<MemberPointerType>();
2510 if (FromMember->getClass() != ToMember->getClass()) {
2511 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2512 << QualType(FromMember->getClass(), 0);
2513 return;
2514 }
2515 FromType = FromMember->getPointeeType();
2516 ToType = ToMember->getPointeeType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00002517 }
2518
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002519 if (FromType->isPointerType())
2520 FromType = FromType->getPointeeType();
2521 if (ToType->isPointerType())
2522 ToType = ToType->getPointeeType();
2523
2524 // Remove references.
Richard Trieu6efd4c52011-11-23 22:32:32 +00002525 FromType = FromType.getNonReferenceType();
2526 ToType = ToType.getNonReferenceType();
2527
Richard Trieu6efd4c52011-11-23 22:32:32 +00002528 // Don't print extra info for non-specialized template functions.
2529 if (FromType->isInstantiationDependentType() &&
2530 !FromType->getAs<TemplateSpecializationType>()) {
2531 PDiag << ft_default;
2532 return;
2533 }
2534
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002535 // No extra info for same types.
2536 if (Context.hasSameType(FromType, ToType)) {
2537 PDiag << ft_default;
2538 return;
2539 }
2540
Richard Trieu6efd4c52011-11-23 22:32:32 +00002541 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2542 *ToFunction = ToType->getAs<FunctionProtoType>();
2543
2544 // Both types need to be function types.
2545 if (!FromFunction || !ToFunction) {
2546 PDiag << ft_default;
2547 return;
2548 }
2549
2550 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2551 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2552 << FromFunction->getNumArgs();
2553 return;
2554 }
2555
2556 // Handle different parameter types.
2557 unsigned ArgPos;
2558 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2559 PDiag << ft_parameter_mismatch << ArgPos + 1
2560 << ToFunction->getArgType(ArgPos)
2561 << FromFunction->getArgType(ArgPos);
2562 return;
2563 }
2564
2565 // Handle different return type.
2566 if (!Context.hasSameType(FromFunction->getResultType(),
2567 ToFunction->getResultType())) {
2568 PDiag << ft_return_type << ToFunction->getResultType()
2569 << FromFunction->getResultType();
2570 return;
2571 }
2572
2573 unsigned FromQuals = FromFunction->getTypeQuals(),
2574 ToQuals = ToFunction->getTypeQuals();
2575 if (FromQuals != ToQuals) {
2576 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2577 return;
2578 }
2579
2580 // Unable to find a difference, so add no extra info.
2581 PDiag << ft_default;
2582}
2583
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002584/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregordec1cc42011-12-15 17:15:07 +00002585/// for equality of their argument types. Caller has already checked that
Eli Friedman06017002013-06-18 22:41:37 +00002586/// they have same number of arguments. If the parameters are different,
2587/// ArgPos will have the parameter index of the first different parameter.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002588bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieu6efd4c52011-11-23 22:32:32 +00002589 const FunctionProtoType *NewType,
2590 unsigned *ArgPos) {
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002591 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2592 N = NewType->arg_type_begin(),
2593 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
Richard Trieu7ea491c2013-08-09 21:42:32 +00002594 if (!Context.hasSameType(O->getUnqualifiedType(),
2595 N->getUnqualifiedType())) {
Larisse Voufo3151b7c2013-08-06 03:57:41 +00002596 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2597 return false;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002598 }
2599 }
2600 return true;
2601}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002602
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002603/// CheckPointerConversion - Check the pointer conversion from the
2604/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002605/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002606/// conversions for which IsPointerConversion has already returned
2607/// true. It returns true and produces a diagnostic if there was an
2608/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00002609bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002610 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002611 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002612 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002613 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00002614 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002615
John McCalldaa8e4e2010-11-15 09:13:47 +00002616 Kind = CK_BitCast;
2617
David Blaikie50800fc2012-08-08 17:33:31 +00002618 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2619 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2620 Expr::NPCK_ZeroExpression) {
2621 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2622 DiagRuntimeBehavior(From->getExprLoc(), From,
2623 PDiag(diag::warn_impcast_bool_to_null_pointer)
2624 << ToType << From->getSourceRange());
2625 else if (!isUnevaluatedContext())
2626 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2627 << ToType << From->getSourceRange();
2628 }
John McCall1d9b3b22011-09-09 05:25:32 +00002629 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2630 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002631 QualType FromPointeeType = FromPtrType->getPointeeType(),
2632 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00002633
Douglas Gregor5fccd362010-03-03 23:55:11 +00002634 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2635 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002636 // We must have a derived-to-base conversion. Check an
2637 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00002638 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2639 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002640 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002641 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00002642 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002643
Anders Carlsson61faec12009-09-12 04:46:44 +00002644 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00002645 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002646 }
2647 }
John McCall1d9b3b22011-09-09 05:25:32 +00002648 } else if (const ObjCObjectPointerType *ToPtrType =
2649 ToType->getAs<ObjCObjectPointerType>()) {
2650 if (const ObjCObjectPointerType *FromPtrType =
2651 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002652 // Objective-C++ conversions are always okay.
2653 // FIXME: We should have a different class of conversions for the
2654 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00002655 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00002656 return false;
John McCall1d9b3b22011-09-09 05:25:32 +00002657 } else if (FromType->isBlockPointerType()) {
2658 Kind = CK_BlockPointerToObjCPointerCast;
2659 } else {
2660 Kind = CK_CPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00002661 }
John McCall1d9b3b22011-09-09 05:25:32 +00002662 } else if (ToType->isBlockPointerType()) {
2663 if (!FromType->isBlockPointerType())
2664 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00002665 }
John McCalldaa8e4e2010-11-15 09:13:47 +00002666
2667 // We shouldn't fall into this case unless it's valid for other
2668 // reasons.
2669 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2670 Kind = CK_NullToPointer;
2671
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002672 return false;
2673}
2674
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002675/// IsMemberPointerConversion - Determines whether the conversion of the
2676/// expression From, which has the (possibly adjusted) type FromType, can be
2677/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2678/// If so, returns true and places the converted type (that might differ from
2679/// ToType in its cv-qualifiers at some level) into ConvertedType.
2680bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002681 QualType ToType,
Douglas Gregorce940492009-09-25 04:25:58 +00002682 bool InOverloadResolution,
2683 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002684 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002685 if (!ToTypePtr)
2686 return false;
2687
2688 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00002689 if (From->isNullPointerConstant(Context,
2690 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2691 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002692 ConvertedType = ToType;
2693 return true;
2694 }
2695
2696 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00002697 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002698 if (!FromTypePtr)
2699 return false;
2700
2701 // A pointer to member of B can be converted to a pointer to member of D,
2702 // where D is derived from B (C++ 4.11p2).
2703 QualType FromClass(FromTypePtr->getClass(), 0);
2704 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002705
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002706 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002707 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002708 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002709 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2710 ToClass.getTypePtr());
2711 return true;
2712 }
2713
2714 return false;
2715}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002716
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002717/// CheckMemberPointerConversion - Check the member pointer conversion from the
2718/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00002719/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002720/// for which IsMemberPointerConversion has already returned true. It returns
2721/// true and produces a diagnostic if there was an error, or returns false
2722/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002723bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002724 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002725 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002726 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002727 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002728 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002729 if (!FromPtrType) {
2730 // This must be a null pointer to member pointer conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002731 assert(From->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00002732 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002733 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00002734 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002735 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002736 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002737
Ted Kremenek6217b802009-07-29 21:53:49 +00002738 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00002739 assert(ToPtrType && "No member pointer cast has a target type "
2740 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002741
Sebastian Redl21593ac2009-01-28 18:33:18 +00002742 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2743 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002744
Sebastian Redl21593ac2009-01-28 18:33:18 +00002745 // FIXME: What about dependent types?
2746 assert(FromClass->isRecordType() && "Pointer into non-class.");
2747 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002748
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002749 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002750 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00002751 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2752 assert(DerivationOkay &&
2753 "Should not have been called if derivation isn't OK.");
2754 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002755
Sebastian Redl21593ac2009-01-28 18:33:18 +00002756 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2757 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002758 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2759 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2760 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2761 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002762 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00002763
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002764 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002765 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2766 << FromClass << ToClass << QualType(VBase, 0)
2767 << From->getSourceRange();
2768 return true;
2769 }
2770
John McCall6b2accb2010-02-10 09:31:12 +00002771 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00002772 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2773 Paths.front(),
2774 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00002775
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002776 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002777 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00002778 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002779 return false;
2780}
2781
Douglas Gregor98cd5992008-10-21 23:43:52 +00002782/// IsQualificationConversion - Determines whether the conversion from
2783/// an rvalue of type FromType to ToType is a qualification conversion
2784/// (C++ 4.4).
John McCallf85e1932011-06-15 23:02:42 +00002785///
2786/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2787/// when the qualification conversion involves a change in the Objective-C
2788/// object lifetime.
Mike Stump1eb44332009-09-09 15:08:12 +00002789bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002790Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00002791 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002792 FromType = Context.getCanonicalType(FromType);
2793 ToType = Context.getCanonicalType(ToType);
John McCallf85e1932011-06-15 23:02:42 +00002794 ObjCLifetimeConversion = false;
2795
Douglas Gregor98cd5992008-10-21 23:43:52 +00002796 // If FromType and ToType are the same type, this is not a
2797 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00002798 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00002799 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002800
Douglas Gregor98cd5992008-10-21 23:43:52 +00002801 // (C++ 4.4p4):
2802 // A conversion can add cv-qualifiers at levels other than the first
2803 // in multi-level pointers, subject to the following rules: [...]
2804 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002805 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002806 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002807 // Within each iteration of the loop, we check the qualifiers to
2808 // determine if this still looks like a qualification
2809 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002810 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00002811 // until there are no more pointers or pointers-to-members left to
2812 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00002813 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002814
Douglas Gregor621c92a2011-04-25 18:40:17 +00002815 Qualifiers FromQuals = FromType.getQualifiers();
2816 Qualifiers ToQuals = ToType.getQualifiers();
2817
John McCallf85e1932011-06-15 23:02:42 +00002818 // Objective-C ARC:
2819 // Check Objective-C lifetime conversions.
2820 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2821 UnwrappedAnyPointer) {
2822 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2823 ObjCLifetimeConversion = true;
2824 FromQuals.removeObjCLifetime();
2825 ToQuals.removeObjCLifetime();
2826 } else {
2827 // Qualification conversions cannot cast between different
2828 // Objective-C lifetime qualifiers.
2829 return false;
2830 }
2831 }
2832
Douglas Gregor377e1bd2011-05-08 06:09:53 +00002833 // Allow addition/removal of GC attributes but not changing GC attributes.
2834 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2835 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2836 FromQuals.removeObjCGCAttr();
2837 ToQuals.removeObjCGCAttr();
2838 }
2839
Douglas Gregor98cd5992008-10-21 23:43:52 +00002840 // -- for every j > 0, if const is in cv 1,j then const is in cv
2841 // 2,j, and similarly for volatile.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002842 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002843 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002844
Douglas Gregor98cd5992008-10-21 23:43:52 +00002845 // -- if the cv 1,j and cv 2,j are different, then const is in
2846 // every cv for 0 < k < j.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002847 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00002848 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00002849 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002850
Douglas Gregor98cd5992008-10-21 23:43:52 +00002851 // Keep track of whether all prior cv-qualifiers in the "to" type
2852 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00002853 PreviousToQualsIncludeConst
Douglas Gregor621c92a2011-04-25 18:40:17 +00002854 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregor57373262008-10-22 14:17:15 +00002855 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00002856
2857 // We are left with FromType and ToType being the pointee types
2858 // after unwrapping the original FromType and ToType the same number
2859 // of types. If we unwrapped any pointers, and if FromType and
2860 // ToType have the same unqualified type (since we checked
2861 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002862 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00002863}
2864
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002865/// \brief - Determine whether this is a conversion from a scalar type to an
2866/// atomic type.
2867///
2868/// If successful, updates \c SCS's second and third steps in the conversion
2869/// sequence to finish the conversion.
Douglas Gregor7d000652012-04-12 20:48:09 +00002870static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2871 bool InOverloadResolution,
2872 StandardConversionSequence &SCS,
2873 bool CStyle) {
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002874 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2875 if (!ToAtomic)
2876 return false;
2877
2878 StandardConversionSequence InnerSCS;
2879 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2880 InOverloadResolution, InnerSCS,
2881 CStyle, /*AllowObjCWritebackConversion=*/false))
2882 return false;
2883
2884 SCS.Second = InnerSCS.Second;
2885 SCS.setToType(1, InnerSCS.getToType(1));
2886 SCS.Third = InnerSCS.Third;
2887 SCS.QualificationIncludesObjCLifetime
2888 = InnerSCS.QualificationIncludesObjCLifetime;
2889 SCS.setToType(2, InnerSCS.getToType(2));
2890 return true;
2891}
2892
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002893static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2894 CXXConstructorDecl *Constructor,
2895 QualType Type) {
2896 const FunctionProtoType *CtorType =
2897 Constructor->getType()->getAs<FunctionProtoType>();
2898 if (CtorType->getNumArgs() > 0) {
2899 QualType FirstArg = CtorType->getArgType(0);
2900 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2901 return true;
2902 }
2903 return false;
2904}
2905
Sebastian Redl56a04282012-02-11 23:51:08 +00002906static OverloadingResult
2907IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2908 CXXRecordDecl *To,
2909 UserDefinedConversionSequence &User,
2910 OverloadCandidateSet &CandidateSet,
2911 bool AllowExplicit) {
David Blaikie3bc93e32012-12-19 00:45:41 +00002912 DeclContext::lookup_result R = S.LookupConstructors(To);
2913 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl56a04282012-02-11 23:51:08 +00002914 Con != ConEnd; ++Con) {
2915 NamedDecl *D = *Con;
2916 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2917
2918 // Find the constructor (which may be a template).
2919 CXXConstructorDecl *Constructor = 0;
2920 FunctionTemplateDecl *ConstructorTmpl
2921 = dyn_cast<FunctionTemplateDecl>(D);
2922 if (ConstructorTmpl)
2923 Constructor
2924 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2925 else
2926 Constructor = cast<CXXConstructorDecl>(D);
2927
2928 bool Usable = !Constructor->isInvalidDecl() &&
2929 S.isInitListConstructor(Constructor) &&
2930 (AllowExplicit || !Constructor->isExplicit());
2931 if (Usable) {
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002932 // If the first argument is (a reference to) the target type,
2933 // suppress conversions.
2934 bool SuppressUserConversions =
2935 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl56a04282012-02-11 23:51:08 +00002936 if (ConstructorTmpl)
2937 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2938 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002939 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002940 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002941 else
2942 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002943 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002944 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002945 }
2946 }
2947
2948 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2949
2950 OverloadCandidateSet::iterator Best;
2951 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2952 case OR_Success: {
2953 // Record the standard conversion we used and the conversion function.
2954 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl56a04282012-02-11 23:51:08 +00002955 QualType ThisType = Constructor->getThisType(S.Context);
2956 // Initializer lists don't have conversions as such.
2957 User.Before.setAsIdentityConversion();
2958 User.HadMultipleCandidates = HadMultipleCandidates;
2959 User.ConversionFunction = Constructor;
2960 User.FoundConversionFunction = Best->FoundDecl;
2961 User.After.setAsIdentityConversion();
2962 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2963 User.After.setAllToTypes(ToType);
2964 return OR_Success;
2965 }
2966
2967 case OR_No_Viable_Function:
2968 return OR_No_Viable_Function;
2969 case OR_Deleted:
2970 return OR_Deleted;
2971 case OR_Ambiguous:
2972 return OR_Ambiguous;
2973 }
2974
2975 llvm_unreachable("Invalid OverloadResult!");
2976}
2977
Douglas Gregor734d9862009-01-30 23:27:23 +00002978/// Determines whether there is a user-defined conversion sequence
2979/// (C++ [over.ics.user]) that converts expression From to the type
2980/// ToType. If such a conversion exists, User will contain the
2981/// user-defined conversion sequence that performs such a conversion
2982/// and this routine will return true. Otherwise, this routine returns
2983/// false and User is unspecified.
2984///
Douglas Gregor734d9862009-01-30 23:27:23 +00002985/// \param AllowExplicit true if the conversion should consider C++0x
2986/// "explicit" conversion functions as well as non-explicit conversion
2987/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00002988static OverloadingResult
2989IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl56a04282012-02-11 23:51:08 +00002990 UserDefinedConversionSequence &User,
2991 OverloadCandidateSet &CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00002992 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002993 // Whether we will only visit constructors.
2994 bool ConstructorsOnly = false;
2995
2996 // If the type we are conversion to is a class type, enumerate its
2997 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00002998 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002999 // C++ [over.match.ctor]p1:
3000 // When objects of class type are direct-initialized (8.5), or
3001 // copy-initialized from an expression of the same or a
3002 // derived class type (8.5), overload resolution selects the
3003 // constructor. [...] For copy-initialization, the candidate
3004 // functions are all the converting constructors (12.3.1) of
3005 // that class. The argument list is the expression-list within
3006 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00003007 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003008 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00003009 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003010 ConstructorsOnly = true;
3011
Benjamin Kramer63b6ebe2012-11-23 17:04:52 +00003012 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidise36bca62011-04-22 17:45:37 +00003013 // RequireCompleteType may have returned true due to some invalid decl
3014 // during template instantiation, but ToType may be complete enough now
3015 // to try to recover.
3016 if (ToType->isIncompleteType()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00003017 // We're not going to find any constructors.
3018 } else if (CXXRecordDecl *ToRecordDecl
3019 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003020
3021 Expr **Args = &From;
3022 unsigned NumArgs = 1;
3023 bool ListInitializing = false;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003024 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramere5753592013-09-09 14:48:42 +00003025 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl56a04282012-02-11 23:51:08 +00003026 OverloadingResult Result = IsInitializerListConstructorConversion(
3027 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3028 if (Result != OR_No_Viable_Function)
3029 return Result;
3030 // Never mind.
3031 CandidateSet.clear();
3032
3033 // If we're list-initializing, we pass the individual elements as
3034 // arguments, not the entire list.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003035 Args = InitList->getInits();
3036 NumArgs = InitList->getNumInits();
3037 ListInitializing = true;
3038 }
3039
David Blaikie3bc93e32012-12-19 00:45:41 +00003040 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3041 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003042 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00003043 NamedDecl *D = *Con;
3044 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3045
Douglas Gregordec06662009-08-21 18:42:58 +00003046 // Find the constructor (which may be a template).
3047 CXXConstructorDecl *Constructor = 0;
3048 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00003049 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00003050 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00003051 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00003052 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3053 else
John McCall9aa472c2010-03-19 07:35:19 +00003054 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003055
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003056 bool Usable = !Constructor->isInvalidDecl();
3057 if (ListInitializing)
3058 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3059 else
3060 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3061 if (Usable) {
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003062 bool SuppressUserConversions = !ConstructorsOnly;
3063 if (SuppressUserConversions && ListInitializing) {
3064 SuppressUserConversions = false;
3065 if (NumArgs == 1) {
3066 // If the first argument is (a reference to) the target type,
3067 // suppress conversions.
Sebastian Redlf78c0f92012-03-27 18:33:03 +00003068 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3069 S.Context, Constructor, ToType);
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003070 }
3071 }
Douglas Gregordec06662009-08-21 18:42:58 +00003072 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00003073 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3074 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003075 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003076 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003077 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00003078 // Allow one user-defined conversion when user specifies a
3079 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00003080 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003081 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003082 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003083 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003084 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003085 }
3086 }
3087
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003088 // Enumerate conversion functions, if we're allowed to.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003089 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003090 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003091 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00003092 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003093 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003094 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003095 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3096 // Add all of the conversion functions as candidates.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003097 std::pair<CXXRecordDecl::conversion_iterator,
3098 CXXRecordDecl::conversion_iterator>
3099 Conversions = FromRecordDecl->getVisibleConversionFunctions();
3100 for (CXXRecordDecl::conversion_iterator
3101 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00003102 DeclAccessPair FoundDecl = I.getPair();
3103 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003104 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3105 if (isa<UsingShadowDecl>(D))
3106 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3107
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003108 CXXConversionDecl *Conv;
3109 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00003110 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3111 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003112 else
John McCall32daa422010-03-31 01:36:47 +00003113 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003114
3115 if (AllowExplicit || !Conv->isExplicit()) {
3116 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00003117 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3118 ActingContext, From, ToType,
3119 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003120 else
John McCall120d63c2010-08-24 20:38:10 +00003121 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3122 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003123 }
3124 }
3125 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003126 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003127
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003128 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3129
Douglas Gregor60d62c22008-10-31 16:23:19 +00003130 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003131 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00003132 case OR_Success:
3133 // Record the standard conversion we used and the conversion function.
3134 if (CXXConstructorDecl *Constructor
3135 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3136 // C++ [over.ics.user]p1:
3137 // If the user-defined conversion is specified by a
3138 // constructor (12.3.1), the initial standard conversion
3139 // sequence converts the source type to the type required by
3140 // the argument of the constructor.
3141 //
3142 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003143 if (isa<InitListExpr>(From)) {
3144 // Initializer lists don't have conversions as such.
3145 User.Before.setAsIdentityConversion();
3146 } else {
3147 if (Best->Conversions[0].isEllipsis())
3148 User.EllipsisConversion = true;
3149 else {
3150 User.Before = Best->Conversions[0].Standard;
3151 User.EllipsisConversion = false;
3152 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003153 }
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003154 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003155 User.ConversionFunction = Constructor;
John McCallca82a822011-09-21 08:36:56 +00003156 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003157 User.After.setAsIdentityConversion();
3158 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3159 User.After.setAllToTypes(ToType);
3160 return OR_Success;
David Blaikie7530c032012-01-17 06:56:22 +00003161 }
3162 if (CXXConversionDecl *Conversion
John McCall120d63c2010-08-24 20:38:10 +00003163 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3164 // C++ [over.ics.user]p1:
3165 //
3166 // [...] If the user-defined conversion is specified by a
3167 // conversion function (12.3.2), the initial standard
3168 // conversion sequence converts the source type to the
3169 // implicit object parameter of the conversion function.
3170 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003171 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003172 User.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00003173 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003174 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003175
John McCall120d63c2010-08-24 20:38:10 +00003176 // C++ [over.ics.user]p2:
3177 // The second standard conversion sequence converts the
3178 // result of the user-defined conversion to the target type
3179 // for the sequence. Since an implicit conversion sequence
3180 // is an initialization, the special rules for
3181 // initialization by user-defined conversion apply when
3182 // selecting the best user-defined conversion for a
3183 // user-defined conversion sequence (see 13.3.3 and
3184 // 13.3.3.1).
3185 User.After = Best->FinalConversion;
3186 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00003187 }
David Blaikie7530c032012-01-17 06:56:22 +00003188 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003189
John McCall120d63c2010-08-24 20:38:10 +00003190 case OR_No_Viable_Function:
3191 return OR_No_Viable_Function;
3192 case OR_Deleted:
3193 // No conversion here! We're done.
3194 return OR_Deleted;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003195
John McCall120d63c2010-08-24 20:38:10 +00003196 case OR_Ambiguous:
3197 return OR_Ambiguous;
3198 }
3199
David Blaikie7530c032012-01-17 06:56:22 +00003200 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003201}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003202
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003203bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003204Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003205 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00003206 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003207 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00003208 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003209 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003210 if (OvResult == OR_Ambiguous)
Daniel Dunbar96a00142012-03-09 18:35:03 +00003211 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003212 diag::err_typecheck_ambiguous_condition)
3213 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo7419d012013-06-27 01:50:25 +00003214 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo288f76a2013-06-27 03:36:30 +00003215 if (!RequireCompleteType(From->getLocStart(), ToType,
Larisse Voufo7419d012013-06-27 01:50:25 +00003216 diag::err_typecheck_nonviable_condition_incomplete,
3217 From->getType(), From->getSourceRange()))
3218 Diag(From->getLocStart(),
3219 diag::err_typecheck_nonviable_condition)
3220 << From->getType() << From->getSourceRange() << ToType;
3221 }
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003222 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003223 return false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003224 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003225 return true;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003226}
Douglas Gregor60d62c22008-10-31 16:23:19 +00003227
Douglas Gregorb734e242012-02-22 17:32:19 +00003228/// \brief Compare the user-defined conversion functions or constructors
3229/// of two user-defined conversion sequences to determine whether any ordering
3230/// is possible.
3231static ImplicitConversionSequence::CompareKind
3232compareConversionFunctions(Sema &S,
3233 FunctionDecl *Function1,
3234 FunctionDecl *Function2) {
Richard Smith80ad52f2013-01-02 11:42:31 +00003235 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregorb734e242012-02-22 17:32:19 +00003236 return ImplicitConversionSequence::Indistinguishable;
3237
3238 // Objective-C++:
3239 // If both conversion functions are implicitly-declared conversions from
3240 // a lambda closure type to a function pointer and a block pointer,
3241 // respectively, always prefer the conversion to a function pointer,
3242 // because the function pointer is more lightweight and is more likely
3243 // to keep code working.
3244 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3245 if (!Conv1)
3246 return ImplicitConversionSequence::Indistinguishable;
3247
3248 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3249 if (!Conv2)
3250 return ImplicitConversionSequence::Indistinguishable;
3251
3252 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3253 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3254 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3255 if (Block1 != Block2)
3256 return Block1? ImplicitConversionSequence::Worse
3257 : ImplicitConversionSequence::Better;
3258 }
3259
3260 return ImplicitConversionSequence::Indistinguishable;
3261}
3262
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003263/// CompareImplicitConversionSequences - Compare two implicit
3264/// conversion sequences to determine whether one is better than the
3265/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00003266static ImplicitConversionSequence::CompareKind
3267CompareImplicitConversionSequences(Sema &S,
3268 const ImplicitConversionSequence& ICS1,
3269 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003270{
3271 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3272 // conversion sequences (as defined in 13.3.3.1)
3273 // -- a standard conversion sequence (13.3.3.1.1) is a better
3274 // conversion sequence than a user-defined conversion sequence or
3275 // an ellipsis conversion sequence, and
3276 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3277 // conversion sequence than an ellipsis conversion sequence
3278 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00003279 //
John McCall1d318332010-01-12 00:44:57 +00003280 // C++0x [over.best.ics]p10:
3281 // For the purpose of ranking implicit conversion sequences as
3282 // described in 13.3.3.2, the ambiguous conversion sequence is
3283 // treated as a user-defined sequence that is indistinguishable
3284 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003285 if (ICS1.getKindRank() < ICS2.getKindRank())
3286 return ImplicitConversionSequence::Better;
David Blaikie7530c032012-01-17 06:56:22 +00003287 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003288 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003289
Benjamin Kramerb6eee072010-04-18 12:05:54 +00003290 // The following checks require both conversion sequences to be of
3291 // the same kind.
3292 if (ICS1.getKind() != ICS2.getKind())
3293 return ImplicitConversionSequence::Indistinguishable;
3294
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003295 ImplicitConversionSequence::CompareKind Result =
3296 ImplicitConversionSequence::Indistinguishable;
3297
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003298 // Two implicit conversion sequences of the same form are
3299 // indistinguishable conversion sequences unless one of the
3300 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00003301 if (ICS1.isStandard())
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003302 Result = CompareStandardConversionSequences(S,
3303 ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00003304 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003305 // User-defined conversion sequence U1 is a better conversion
3306 // sequence than another user-defined conversion sequence U2 if
3307 // they contain the same user-defined conversion function or
3308 // constructor and if the second standard conversion sequence of
3309 // U1 is better than the second standard conversion sequence of
3310 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00003311 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003312 ICS2.UserDefined.ConversionFunction)
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003313 Result = CompareStandardConversionSequences(S,
3314 ICS1.UserDefined.After,
3315 ICS2.UserDefined.After);
Douglas Gregorb734e242012-02-22 17:32:19 +00003316 else
3317 Result = compareConversionFunctions(S,
3318 ICS1.UserDefined.ConversionFunction,
3319 ICS2.UserDefined.ConversionFunction);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003320 }
3321
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003322 // List-initialization sequence L1 is a better conversion sequence than
3323 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3324 // for some X and L2 does not.
3325 if (Result == ImplicitConversionSequence::Indistinguishable &&
Richard Smith798186a2013-09-06 22:30:28 +00003326 !ICS1.isBad()) {
Sebastian Redladfb5352012-02-27 22:38:26 +00003327 if (ICS1.isStdInitializerListElement() &&
3328 !ICS2.isStdInitializerListElement())
3329 return ImplicitConversionSequence::Better;
3330 if (!ICS1.isStdInitializerListElement() &&
3331 ICS2.isStdInitializerListElement())
3332 return ImplicitConversionSequence::Worse;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003333 }
3334
3335 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003336}
3337
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003338static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3339 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3340 Qualifiers Quals;
3341 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003342 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003343 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003344
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003345 return Context.hasSameUnqualifiedType(T1, T2);
3346}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003347
Douglas Gregorad323a82010-01-27 03:51:04 +00003348// Per 13.3.3.2p3, compare the given standard conversion sequences to
3349// determine if one is a proper subset of the other.
3350static ImplicitConversionSequence::CompareKind
3351compareStandardConversionSubsets(ASTContext &Context,
3352 const StandardConversionSequence& SCS1,
3353 const StandardConversionSequence& SCS2) {
3354 ImplicitConversionSequence::CompareKind Result
3355 = ImplicitConversionSequence::Indistinguishable;
3356
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003357 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregorae65f4b2010-05-23 22:10:15 +00003358 // any non-identity conversion sequence
Douglas Gregor4ae5b722011-06-05 06:15:20 +00003359 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3360 return ImplicitConversionSequence::Better;
3361 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3362 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003363
Douglas Gregorad323a82010-01-27 03:51:04 +00003364 if (SCS1.Second != SCS2.Second) {
3365 if (SCS1.Second == ICK_Identity)
3366 Result = ImplicitConversionSequence::Better;
3367 else if (SCS2.Second == ICK_Identity)
3368 Result = ImplicitConversionSequence::Worse;
3369 else
3370 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003371 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00003372 return ImplicitConversionSequence::Indistinguishable;
3373
3374 if (SCS1.Third == SCS2.Third) {
3375 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3376 : ImplicitConversionSequence::Indistinguishable;
3377 }
3378
3379 if (SCS1.Third == ICK_Identity)
3380 return Result == ImplicitConversionSequence::Worse
3381 ? ImplicitConversionSequence::Indistinguishable
3382 : ImplicitConversionSequence::Better;
3383
3384 if (SCS2.Third == ICK_Identity)
3385 return Result == ImplicitConversionSequence::Better
3386 ? ImplicitConversionSequence::Indistinguishable
3387 : ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003388
Douglas Gregorad323a82010-01-27 03:51:04 +00003389 return ImplicitConversionSequence::Indistinguishable;
3390}
3391
Douglas Gregor440a4832011-01-26 14:52:12 +00003392/// \brief Determine whether one of the given reference bindings is better
3393/// than the other based on what kind of bindings they are.
3394static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3395 const StandardConversionSequence &SCS2) {
3396 // C++0x [over.ics.rank]p3b4:
3397 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3398 // implicit object parameter of a non-static member function declared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003399 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregor440a4832011-01-26 14:52:12 +00003400 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003401 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregor440a4832011-01-26 14:52:12 +00003402 // reference*.
3403 //
3404 // FIXME: Rvalue references. We're going rogue with the above edits,
3405 // because the semantics in the current C++0x working paper (N3225 at the
3406 // time of this writing) break the standard definition of std::forward
3407 // and std::reference_wrapper when dealing with references to functions.
3408 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003409 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3410 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3411 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003412
Douglas Gregor440a4832011-01-26 14:52:12 +00003413 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3414 SCS2.IsLvalueReference) ||
3415 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3416 !SCS2.IsLvalueReference);
3417}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003418
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003419/// CompareStandardConversionSequences - Compare two standard
3420/// conversion sequences to determine whether one is better than the
3421/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00003422static ImplicitConversionSequence::CompareKind
3423CompareStandardConversionSequences(Sema &S,
3424 const StandardConversionSequence& SCS1,
3425 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003426{
3427 // Standard conversion sequence S1 is a better conversion sequence
3428 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3429
3430 // -- S1 is a proper subsequence of S2 (comparing the conversion
3431 // sequences in the canonical form defined by 13.3.3.1.1,
3432 // excluding any Lvalue Transformation; the identity conversion
3433 // sequence is considered to be a subsequence of any
3434 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00003435 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00003436 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00003437 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003438
3439 // -- the rank of S1 is better than the rank of S2 (by the rules
3440 // defined below), or, if not that,
3441 ImplicitConversionRank Rank1 = SCS1.getRank();
3442 ImplicitConversionRank Rank2 = SCS2.getRank();
3443 if (Rank1 < Rank2)
3444 return ImplicitConversionSequence::Better;
3445 else if (Rank2 < Rank1)
3446 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003447
Douglas Gregor57373262008-10-22 14:17:15 +00003448 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3449 // are indistinguishable unless one of the following rules
3450 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00003451
Douglas Gregor57373262008-10-22 14:17:15 +00003452 // A conversion that is not a conversion of a pointer, or
3453 // pointer to member, to bool is better than another conversion
3454 // that is such a conversion.
3455 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3456 return SCS2.isPointerConversionToBool()
3457 ? ImplicitConversionSequence::Better
3458 : ImplicitConversionSequence::Worse;
3459
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003460 // C++ [over.ics.rank]p4b2:
3461 //
3462 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003463 // conversion of B* to A* is better than conversion of B* to
3464 // void*, and conversion of A* to void* is better than conversion
3465 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00003466 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003467 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003468 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003469 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003470 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3471 // Exactly one of the conversion sequences is a conversion to
3472 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003473 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3474 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003475 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3476 // Neither conversion sequence converts to a void pointer; compare
3477 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003478 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00003479 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003480 return DerivedCK;
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003481 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3482 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003483 // Both conversion sequences are conversions to void
3484 // pointers. Compare the source types to determine if there's an
3485 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00003486 QualType FromType1 = SCS1.getFromType();
3487 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003488
3489 // Adjust the types we're converting from via the array-to-pointer
3490 // conversion, if we need to.
3491 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003492 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003493 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003494 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003495
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003496 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3497 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003498
John McCall120d63c2010-08-24 20:38:10 +00003499 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00003500 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003501 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00003502 return ImplicitConversionSequence::Worse;
3503
3504 // Objective-C++: If one interface is more specific than the
3505 // other, it is the better one.
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003506 const ObjCObjectPointerType* FromObjCPtr1
3507 = FromType1->getAs<ObjCObjectPointerType>();
3508 const ObjCObjectPointerType* FromObjCPtr2
3509 = FromType2->getAs<ObjCObjectPointerType>();
3510 if (FromObjCPtr1 && FromObjCPtr2) {
3511 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3512 FromObjCPtr2);
3513 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3514 FromObjCPtr1);
3515 if (AssignLeft != AssignRight) {
3516 return AssignLeft? ImplicitConversionSequence::Better
3517 : ImplicitConversionSequence::Worse;
3518 }
Douglas Gregor01919692009-12-13 21:37:05 +00003519 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003520 }
Douglas Gregor57373262008-10-22 14:17:15 +00003521
3522 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3523 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00003524 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00003525 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003526 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00003527
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003528 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregor440a4832011-01-26 14:52:12 +00003529 // Check for a better reference binding based on the kind of bindings.
3530 if (isBetterReferenceBindingKind(SCS1, SCS2))
3531 return ImplicitConversionSequence::Better;
3532 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3533 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003534
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003535 // C++ [over.ics.rank]p3b4:
3536 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3537 // which the references refer are the same type except for
3538 // top-level cv-qualifiers, and the type to which the reference
3539 // initialized by S2 refers is more cv-qualified than the type
3540 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00003541 QualType T1 = SCS1.getToType(2);
3542 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003543 T1 = S.Context.getCanonicalType(T1);
3544 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003545 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003546 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3547 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003548 if (UnqualT1 == UnqualT2) {
John McCallf85e1932011-06-15 23:02:42 +00003549 // Objective-C++ ARC: If the references refer to objects with different
3550 // lifetimes, prefer bindings that don't change lifetime.
3551 if (SCS1.ObjCLifetimeConversionBinding !=
3552 SCS2.ObjCLifetimeConversionBinding) {
3553 return SCS1.ObjCLifetimeConversionBinding
3554 ? ImplicitConversionSequence::Worse
3555 : ImplicitConversionSequence::Better;
3556 }
3557
Chandler Carruth6df868e2010-12-12 08:17:55 +00003558 // If the type is an array type, promote the element qualifiers to the
3559 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003560 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003561 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003562 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003563 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003564 if (T2.isMoreQualifiedThan(T1))
3565 return ImplicitConversionSequence::Better;
3566 else if (T1.isMoreQualifiedThan(T2))
John McCallf85e1932011-06-15 23:02:42 +00003567 return ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003568 }
3569 }
Douglas Gregor57373262008-10-22 14:17:15 +00003570
Francois Pichet1c98d622011-09-18 21:37:37 +00003571 // In Microsoft mode, prefer an integral conversion to a
3572 // floating-to-integral conversion if the integral conversion
3573 // is between types of the same size.
3574 // For example:
3575 // void f(float);
3576 // void f(int);
3577 // int main {
3578 // long a;
3579 // f(a);
3580 // }
3581 // Here, MSVC will call f(int) instead of generating a compile error
3582 // as clang will do in standard mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00003583 if (S.getLangOpts().MicrosoftMode &&
Francois Pichet1c98d622011-09-18 21:37:37 +00003584 SCS1.Second == ICK_Integral_Conversion &&
3585 SCS2.Second == ICK_Floating_Integral &&
3586 S.Context.getTypeSize(SCS1.getFromType()) ==
3587 S.Context.getTypeSize(SCS1.getToType(2)))
3588 return ImplicitConversionSequence::Better;
3589
Douglas Gregor57373262008-10-22 14:17:15 +00003590 return ImplicitConversionSequence::Indistinguishable;
3591}
3592
3593/// CompareQualificationConversions - Compares two standard conversion
3594/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00003595/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3596ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003597CompareQualificationConversions(Sema &S,
3598 const StandardConversionSequence& SCS1,
3599 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00003600 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00003601 // -- S1 and S2 differ only in their qualification conversion and
3602 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3603 // cv-qualification signature of type T1 is a proper subset of
3604 // the cv-qualification signature of type T2, and S1 is not the
3605 // deprecated string literal array-to-pointer conversion (4.2).
3606 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3607 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3608 return ImplicitConversionSequence::Indistinguishable;
3609
3610 // FIXME: the example in the standard doesn't use a qualification
3611 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00003612 QualType T1 = SCS1.getToType(2);
3613 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003614 T1 = S.Context.getCanonicalType(T1);
3615 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003616 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003617 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3618 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00003619
3620 // If the types are the same, we won't learn anything by unwrapped
3621 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003622 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00003623 return ImplicitConversionSequence::Indistinguishable;
3624
Chandler Carruth28e318c2009-12-29 07:16:59 +00003625 // If the type is an array type, promote the element qualifiers to the type
3626 // for comparison.
3627 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003628 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003629 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003630 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003631
Mike Stump1eb44332009-09-09 15:08:12 +00003632 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00003633 = ImplicitConversionSequence::Indistinguishable;
John McCallf85e1932011-06-15 23:02:42 +00003634
3635 // Objective-C++ ARC:
3636 // Prefer qualification conversions not involving a change in lifetime
3637 // to qualification conversions that do not change lifetime.
3638 if (SCS1.QualificationIncludesObjCLifetime !=
3639 SCS2.QualificationIncludesObjCLifetime) {
3640 Result = SCS1.QualificationIncludesObjCLifetime
3641 ? ImplicitConversionSequence::Worse
3642 : ImplicitConversionSequence::Better;
3643 }
3644
John McCall120d63c2010-08-24 20:38:10 +00003645 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00003646 // Within each iteration of the loop, we check the qualifiers to
3647 // determine if this still looks like a qualification
3648 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00003649 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00003650 // until there are no more pointers or pointers-to-members left
3651 // to unwrap. This essentially mimics what
3652 // IsQualificationConversion does, but here we're checking for a
3653 // strict subset of qualifiers.
3654 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3655 // The qualifiers are the same, so this doesn't tell us anything
3656 // about how the sequences rank.
3657 ;
3658 else if (T2.isMoreQualifiedThan(T1)) {
3659 // T1 has fewer qualifiers, so it could be the better sequence.
3660 if (Result == ImplicitConversionSequence::Worse)
3661 // Neither has qualifiers that are a subset of the other's
3662 // qualifiers.
3663 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003664
Douglas Gregor57373262008-10-22 14:17:15 +00003665 Result = ImplicitConversionSequence::Better;
3666 } else if (T1.isMoreQualifiedThan(T2)) {
3667 // T2 has fewer qualifiers, so it could be the better sequence.
3668 if (Result == ImplicitConversionSequence::Better)
3669 // Neither has qualifiers that are a subset of the other's
3670 // qualifiers.
3671 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003672
Douglas Gregor57373262008-10-22 14:17:15 +00003673 Result = ImplicitConversionSequence::Worse;
3674 } else {
3675 // Qualifiers are disjoint.
3676 return ImplicitConversionSequence::Indistinguishable;
3677 }
3678
3679 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00003680 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00003681 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003682 }
3683
Douglas Gregor57373262008-10-22 14:17:15 +00003684 // Check that the winning standard conversion sequence isn't using
3685 // the deprecated string literal array to pointer conversion.
3686 switch (Result) {
3687 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00003688 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003689 Result = ImplicitConversionSequence::Indistinguishable;
3690 break;
3691
3692 case ImplicitConversionSequence::Indistinguishable:
3693 break;
3694
3695 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00003696 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003697 Result = ImplicitConversionSequence::Indistinguishable;
3698 break;
3699 }
3700
3701 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003702}
3703
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003704/// CompareDerivedToBaseConversions - Compares two standard conversion
3705/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00003706/// various kinds of derived-to-base conversions (C++
3707/// [over.ics.rank]p4b3). As part of these checks, we also look at
3708/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003709ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003710CompareDerivedToBaseConversions(Sema &S,
3711 const StandardConversionSequence& SCS1,
3712 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00003713 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003714 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00003715 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003716 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003717
3718 // Adjust the types we're converting from via the array-to-pointer
3719 // conversion, if we need to.
3720 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003721 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003722 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003723 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003724
3725 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00003726 FromType1 = S.Context.getCanonicalType(FromType1);
3727 ToType1 = S.Context.getCanonicalType(ToType1);
3728 FromType2 = S.Context.getCanonicalType(FromType2);
3729 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003730
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003731 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003732 //
3733 // If class B is derived directly or indirectly from class A and
3734 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00003735 //
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003736 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00003737 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00003738 SCS2.Second == ICK_Pointer_Conversion &&
3739 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3740 FromType1->isPointerType() && FromType2->isPointerType() &&
3741 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003742 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003743 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00003744 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003745 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003746 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003747 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003748 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003749 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00003750
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003751 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003752 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003753 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003754 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003755 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003756 return ImplicitConversionSequence::Worse;
3757 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003758
3759 // -- conversion of B* to A* is better than conversion of C* to A*,
3760 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003761 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003762 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003763 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003764 return ImplicitConversionSequence::Worse;
Douglas Gregor395cc372011-01-31 18:51:41 +00003765 }
3766 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3767 SCS2.Second == ICK_Pointer_Conversion) {
3768 const ObjCObjectPointerType *FromPtr1
3769 = FromType1->getAs<ObjCObjectPointerType>();
3770 const ObjCObjectPointerType *FromPtr2
3771 = FromType2->getAs<ObjCObjectPointerType>();
3772 const ObjCObjectPointerType *ToPtr1
3773 = ToType1->getAs<ObjCObjectPointerType>();
3774 const ObjCObjectPointerType *ToPtr2
3775 = ToType2->getAs<ObjCObjectPointerType>();
3776
3777 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3778 // Apply the same conversion ranking rules for Objective-C pointer types
3779 // that we do for C++ pointers to class types. However, we employ the
3780 // Objective-C pseudo-subtyping relationship used for assignment of
3781 // Objective-C pointer types.
3782 bool FromAssignLeft
3783 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3784 bool FromAssignRight
3785 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3786 bool ToAssignLeft
3787 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3788 bool ToAssignRight
3789 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3790
3791 // A conversion to an a non-id object pointer type or qualified 'id'
3792 // type is better than a conversion to 'id'.
3793 if (ToPtr1->isObjCIdType() &&
3794 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3795 return ImplicitConversionSequence::Worse;
3796 if (ToPtr2->isObjCIdType() &&
3797 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3798 return ImplicitConversionSequence::Better;
3799
3800 // A conversion to a non-id object pointer type is better than a
3801 // conversion to a qualified 'id' type
3802 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3803 return ImplicitConversionSequence::Worse;
3804 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3805 return ImplicitConversionSequence::Better;
3806
3807 // A conversion to an a non-Class object pointer type or qualified 'Class'
3808 // type is better than a conversion to 'Class'.
3809 if (ToPtr1->isObjCClassType() &&
3810 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3811 return ImplicitConversionSequence::Worse;
3812 if (ToPtr2->isObjCClassType() &&
3813 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3814 return ImplicitConversionSequence::Better;
3815
3816 // A conversion to a non-Class object pointer type is better than a
3817 // conversion to a qualified 'Class' type.
3818 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3819 return ImplicitConversionSequence::Worse;
3820 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3821 return ImplicitConversionSequence::Better;
Mike Stump1eb44332009-09-09 15:08:12 +00003822
Douglas Gregor395cc372011-01-31 18:51:41 +00003823 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3824 if (S.Context.hasSameType(FromType1, FromType2) &&
3825 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3826 (ToAssignLeft != ToAssignRight))
3827 return ToAssignLeft? ImplicitConversionSequence::Worse
3828 : ImplicitConversionSequence::Better;
3829
3830 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3831 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3832 (FromAssignLeft != FromAssignRight))
3833 return FromAssignLeft? ImplicitConversionSequence::Better
3834 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003835 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003836 }
Douglas Gregor395cc372011-01-31 18:51:41 +00003837
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003838 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003839 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3840 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3841 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003842 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003843 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003844 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003845 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003846 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003847 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003848 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003849 ToType2->getAs<MemberPointerType>();
3850 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3851 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3852 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3853 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3854 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3855 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3856 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3857 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003858 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003859 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003860 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003861 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00003862 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003863 return ImplicitConversionSequence::Better;
3864 }
3865 // conversion of B::* to C::* is better than conversion of A::* to C::*
3866 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003867 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003868 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003869 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003870 return ImplicitConversionSequence::Worse;
3871 }
3872 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003873
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003874 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00003875 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00003876 // -- binding of an expression of type C to a reference of type
3877 // B& is better than binding an expression of type C to a
3878 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003879 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3880 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3881 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003882 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003883 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003884 return ImplicitConversionSequence::Worse;
3885 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003886
Douglas Gregor225c41e2008-11-03 19:09:14 +00003887 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00003888 // -- binding of an expression of type B to a reference of type
3889 // A& is better than binding an expression of type C to a
3890 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003891 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3892 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3893 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003894 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003895 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003896 return ImplicitConversionSequence::Worse;
3897 }
3898 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003899
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003900 return ImplicitConversionSequence::Indistinguishable;
3901}
3902
Douglas Gregor0162c1c2013-03-26 23:36:30 +00003903/// \brief Determine whether the given type is valid, e.g., it is not an invalid
3904/// C++ class.
3905static bool isTypeValid(QualType T) {
3906 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3907 return !Record->isInvalidDecl();
3908
3909 return true;
3910}
3911
Douglas Gregorabe183d2010-04-13 16:31:36 +00003912/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3913/// determine whether they are reference-related,
3914/// reference-compatible, reference-compatible with added
3915/// qualification, or incompatible, for use in C++ initialization by
3916/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3917/// type, and the first type (T1) is the pointee type of the reference
3918/// type being initialized.
3919Sema::ReferenceCompareResult
3920Sema::CompareReferenceRelationship(SourceLocation Loc,
3921 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00003922 bool &DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003923 bool &ObjCConversion,
3924 bool &ObjCLifetimeConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003925 assert(!OrigT1->isReferenceType() &&
3926 "T1 must be the pointee type of the reference type");
3927 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3928
3929 QualType T1 = Context.getCanonicalType(OrigT1);
3930 QualType T2 = Context.getCanonicalType(OrigT2);
3931 Qualifiers T1Quals, T2Quals;
3932 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3933 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3934
3935 // C++ [dcl.init.ref]p4:
3936 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3937 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3938 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00003939 DerivedToBase = false;
3940 ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003941 ObjCLifetimeConversion = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003942 if (UnqualT1 == UnqualT2) {
3943 // Nothing to do.
Douglas Gregord10099e2012-05-04 16:32:21 +00003944 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor0162c1c2013-03-26 23:36:30 +00003945 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
3946 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregorabe183d2010-04-13 16:31:36 +00003947 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00003948 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3949 UnqualT2->isObjCObjectOrInterfaceType() &&
3950 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3951 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003952 else
3953 return Ref_Incompatible;
3954
3955 // At this point, we know that T1 and T2 are reference-related (at
3956 // least).
3957
3958 // If the type is an array type, promote the element qualifiers to the type
3959 // for comparison.
3960 if (isa<ArrayType>(T1) && T1Quals)
3961 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3962 if (isa<ArrayType>(T2) && T2Quals)
3963 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3964
3965 // C++ [dcl.init.ref]p4:
3966 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3967 // reference-related to T2 and cv1 is the same cv-qualification
3968 // as, or greater cv-qualification than, cv2. For purposes of
3969 // overload resolution, cases for which cv1 is greater
3970 // cv-qualification than cv2 are identified as
3971 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003972 //
3973 // Note that we also require equivalence of Objective-C GC and address-space
3974 // qualifiers when performing these computations, so that e.g., an int in
3975 // address space 1 is not reference-compatible with an int in address
3976 // space 2.
John McCallf85e1932011-06-15 23:02:42 +00003977 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3978 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3979 T1Quals.removeObjCLifetime();
3980 T2Quals.removeObjCLifetime();
3981 ObjCLifetimeConversion = true;
3982 }
3983
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003984 if (T1Quals == T2Quals)
Douglas Gregorabe183d2010-04-13 16:31:36 +00003985 return Ref_Compatible;
John McCallf85e1932011-06-15 23:02:42 +00003986 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregorabe183d2010-04-13 16:31:36 +00003987 return Ref_Compatible_With_Added_Qualification;
3988 else
3989 return Ref_Related;
3990}
3991
Douglas Gregor604eb652010-08-11 02:15:33 +00003992/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00003993/// with DeclType. Return true if something definite is found.
3994static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00003995FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3996 QualType DeclType, SourceLocation DeclLoc,
3997 Expr *Init, QualType T2, bool AllowRvalues,
3998 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003999 assert(T2->isRecordType() && "Can only find conversions of record types.");
4000 CXXRecordDecl *T2RecordDecl
4001 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4002
4003 OverloadCandidateSet CandidateSet(DeclLoc);
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00004004 std::pair<CXXRecordDecl::conversion_iterator,
4005 CXXRecordDecl::conversion_iterator>
4006 Conversions = T2RecordDecl->getVisibleConversionFunctions();
4007 for (CXXRecordDecl::conversion_iterator
4008 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004009 NamedDecl *D = *I;
4010 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4011 if (isa<UsingShadowDecl>(D))
4012 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4013
4014 FunctionTemplateDecl *ConvTemplate
4015 = dyn_cast<FunctionTemplateDecl>(D);
4016 CXXConversionDecl *Conv;
4017 if (ConvTemplate)
4018 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4019 else
4020 Conv = cast<CXXConversionDecl>(D);
4021
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004022 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor604eb652010-08-11 02:15:33 +00004023 // explicit conversions, skip it.
4024 if (!AllowExplicit && Conv->isExplicit())
4025 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004026
Douglas Gregor604eb652010-08-11 02:15:33 +00004027 if (AllowRvalues) {
4028 bool DerivedToBase = false;
4029 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004030 bool ObjCLifetimeConversion = false;
Douglas Gregor203050c2011-10-04 23:59:32 +00004031
4032 // If we are initializing an rvalue reference, don't permit conversion
4033 // functions that return lvalues.
4034 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4035 const ReferenceType *RefType
4036 = Conv->getConversionType()->getAs<LValueReferenceType>();
4037 if (RefType && !RefType->getPointeeType()->isFunctionType())
4038 continue;
4039 }
4040
Douglas Gregor604eb652010-08-11 02:15:33 +00004041 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00004042 S.CompareReferenceRelationship(
4043 DeclLoc,
4044 Conv->getConversionType().getNonReferenceType()
4045 .getUnqualifiedType(),
4046 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCallf85e1932011-06-15 23:02:42 +00004047 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth6df868e2010-12-12 08:17:55 +00004048 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-08-11 02:15:33 +00004049 continue;
4050 } else {
4051 // If the conversion function doesn't return a reference type,
4052 // it can't be considered for this conversion. An rvalue reference
4053 // is only acceptable if its referencee is a function type.
4054
4055 const ReferenceType *RefType =
4056 Conv->getConversionType()->getAs<ReferenceType>();
4057 if (!RefType ||
4058 (!RefType->isLValueReferenceType() &&
4059 !RefType->getPointeeType()->isFunctionType()))
4060 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004061 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004062
Douglas Gregor604eb652010-08-11 02:15:33 +00004063 if (ConvTemplate)
4064 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004065 Init, DeclType, CandidateSet);
Douglas Gregor604eb652010-08-11 02:15:33 +00004066 else
4067 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004068 DeclType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00004069 }
4070
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004071 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4072
Sebastian Redl4680bf22010-06-30 18:13:39 +00004073 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004074 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004075 case OR_Success:
4076 // C++ [over.ics.ref]p1:
4077 //
4078 // [...] If the parameter binds directly to the result of
4079 // applying a conversion function to the argument
4080 // expression, the implicit conversion sequence is a
4081 // user-defined conversion sequence (13.3.3.1.2), with the
4082 // second standard conversion sequence either an identity
4083 // conversion or, if the conversion function returns an
4084 // entity of a type that is a derived class of the parameter
4085 // type, a derived-to-base Conversion.
4086 if (!Best->FinalConversion.DirectBinding)
4087 return false;
4088
4089 ICS.setUserDefined();
4090 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4091 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004092 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004093 ICS.UserDefined.ConversionFunction = Best->Function;
John McCallca82a822011-09-21 08:36:56 +00004094 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004095 ICS.UserDefined.EllipsisConversion = false;
4096 assert(ICS.UserDefined.After.ReferenceBinding &&
4097 ICS.UserDefined.After.DirectBinding &&
4098 "Expected a direct reference binding!");
4099 return true;
4100
4101 case OR_Ambiguous:
4102 ICS.setAmbiguous();
4103 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4104 Cand != CandidateSet.end(); ++Cand)
4105 if (Cand->Viable)
4106 ICS.Ambiguous.addConversion(Cand->Function);
4107 return true;
4108
4109 case OR_No_Viable_Function:
4110 case OR_Deleted:
4111 // There was no suitable conversion, or we found a deleted
4112 // conversion; continue with other checks.
4113 return false;
4114 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004115
David Blaikie7530c032012-01-17 06:56:22 +00004116 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redl4680bf22010-06-30 18:13:39 +00004117}
4118
Douglas Gregorabe183d2010-04-13 16:31:36 +00004119/// \brief Compute an implicit conversion sequence for reference
4120/// initialization.
4121static ImplicitConversionSequence
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004122TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004123 SourceLocation DeclLoc,
4124 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00004125 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004126 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4127
4128 // Most paths end in a failed conversion.
4129 ImplicitConversionSequence ICS;
4130 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4131
4132 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4133 QualType T2 = Init->getType();
4134
4135 // If the initializer is the address of an overloaded function, try
4136 // to resolve the overloaded function. If all goes well, T2 is the
4137 // type of the resulting function.
4138 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4139 DeclAccessPair Found;
4140 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4141 false, Found))
4142 T2 = Fn->getType();
4143 }
4144
4145 // Compute some basic properties of the types and the initializer.
4146 bool isRValRef = DeclType->isRValueReferenceType();
4147 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00004148 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004149 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004150 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004151 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00004152 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00004153 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004154
Douglas Gregorabe183d2010-04-13 16:31:36 +00004155
Sebastian Redl4680bf22010-06-30 18:13:39 +00004156 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00004157 // A reference to type "cv1 T1" is initialized by an expression
4158 // of type "cv2 T2" as follows:
4159
Sebastian Redl4680bf22010-06-30 18:13:39 +00004160 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004161 if (!isRValRef) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004162 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4163 // reference-compatible with "cv2 T2," or
4164 //
4165 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4166 if (InitCategory.isLValue() &&
4167 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004168 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00004169 // When a parameter of reference type binds directly (8.5.3)
4170 // to an argument expression, the implicit conversion sequence
4171 // is the identity conversion, unless the argument expression
4172 // has a type that is a derived class of the parameter type,
4173 // in which case the implicit conversion sequence is a
4174 // derived-to-base Conversion (13.3.3.1).
4175 ICS.setStandard();
4176 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00004177 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4178 : ObjCConversion? ICK_Compatible_Conversion
4179 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004180 ICS.Standard.Third = ICK_Identity;
4181 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4182 ICS.Standard.setToType(0, T2);
4183 ICS.Standard.setToType(1, T1);
4184 ICS.Standard.setToType(2, T1);
4185 ICS.Standard.ReferenceBinding = true;
4186 ICS.Standard.DirectBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004187 ICS.Standard.IsLvalueReference = !isRValRef;
4188 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4189 ICS.Standard.BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004190 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004191 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004192 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004193
Sebastian Redl4680bf22010-06-30 18:13:39 +00004194 // Nothing more to do: the inaccessibility/ambiguity check for
4195 // derived-to-base conversions is suppressed when we're
4196 // computing the implicit conversion sequence (C++
4197 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00004198 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004199 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00004200
Sebastian Redl4680bf22010-06-30 18:13:39 +00004201 // -- has a class type (i.e., T2 is a class type), where T1 is
4202 // not reference-related to T2, and can be implicitly
4203 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4204 // is reference-compatible with "cv3 T3" 92) (this
4205 // conversion is selected by enumerating the applicable
4206 // conversion functions (13.3.1.6) and choosing the best
4207 // one through overload resolution (13.3)),
4208 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004209 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redl4680bf22010-06-30 18:13:39 +00004210 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00004211 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4212 Init, T2, /*AllowRvalues=*/false,
4213 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00004214 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004215 }
4216 }
4217
Sebastian Redl4680bf22010-06-30 18:13:39 +00004218 // -- Otherwise, the reference shall be an lvalue reference to a
4219 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004220 // shall be an rvalue reference.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004221 //
Douglas Gregor66821b52010-04-18 09:22:00 +00004222 // We actually handle one oddity of C++ [over.ics.ref] at this
4223 // point, which is that, due to p2 (which short-circuits reference
4224 // binding by only attempting a simple conversion for non-direct
4225 // bindings) and p3's strange wording, we allow a const volatile
4226 // reference to bind to an rvalue. Hence the check for the presence
4227 // of "const" rather than checking for "const" being the only
4228 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00004229 // This is also the point where rvalue references and lvalue inits no longer
4230 // go together.
Richard Smith8ab10aa2012-05-24 04:29:20 +00004231 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregorabe183d2010-04-13 16:31:36 +00004232 return ICS;
4233
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004234 // -- If the initializer expression
4235 //
4236 // -- is an xvalue, class prvalue, array prvalue or function
John McCallf85e1932011-06-15 23:02:42 +00004237 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004238 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4239 (InitCategory.isXValue() ||
4240 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4241 (InitCategory.isLValue() && T2->isFunctionType()))) {
4242 ICS.setStandard();
4243 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004244 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004245 : ObjCConversion? ICK_Compatible_Conversion
4246 : ICK_Identity;
4247 ICS.Standard.Third = ICK_Identity;
4248 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4249 ICS.Standard.setToType(0, T2);
4250 ICS.Standard.setToType(1, T1);
4251 ICS.Standard.setToType(2, T1);
4252 ICS.Standard.ReferenceBinding = true;
4253 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4254 // binding unless we're binding to a class prvalue.
4255 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4256 // allow the use of rvalue references in C++98/03 for the benefit of
4257 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004258 ICS.Standard.DirectBinding =
Richard Smith80ad52f2013-01-02 11:42:31 +00004259 S.getLangOpts().CPlusPlus11 ||
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004260 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregor440a4832011-01-26 14:52:12 +00004261 ICS.Standard.IsLvalueReference = !isRValRef;
4262 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004263 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004264 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004265 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004266 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004267 return ICS;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004268 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004269
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004270 // -- has a class type (i.e., T2 is a class type), where T1 is not
4271 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004272 // an xvalue, class prvalue, or function lvalue of type
4273 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004274 // "cv3 T3",
4275 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004276 // then the reference is bound to the value of the initializer
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004277 // expression in the first case and to the result of the conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004278 // in the second case (or, in either case, to an appropriate base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004279 // class subobject).
4280 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004281 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004282 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4283 Init, T2, /*AllowRvalues=*/true,
4284 AllowExplicit)) {
4285 // In the second case, if the reference is an rvalue reference
4286 // and the second standard conversion sequence of the
4287 // user-defined conversion sequence includes an lvalue-to-rvalue
4288 // conversion, the program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004289 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004290 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4291 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4292
Douglas Gregor68ed68b2011-01-21 16:36:05 +00004293 return ICS;
Rafael Espindolaaa5952c2011-01-22 15:32:35 +00004294 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004295
Douglas Gregorabe183d2010-04-13 16:31:36 +00004296 // -- Otherwise, a temporary of type "cv1 T1" is created and
4297 // initialized from the initializer expression using the
4298 // rules for a non-reference copy initialization (8.5). The
4299 // reference is then bound to the temporary. If T1 is
4300 // reference-related to T2, cv1 must be the same
4301 // cv-qualification as, or greater cv-qualification than,
4302 // cv2; otherwise, the program is ill-formed.
4303 if (RefRelationship == Sema::Ref_Related) {
4304 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4305 // we would be reference-compatible or reference-compatible with
4306 // added qualification. But that wasn't the case, so the reference
4307 // initialization fails.
John McCallf85e1932011-06-15 23:02:42 +00004308 //
4309 // Note that we only want to check address spaces and cvr-qualifiers here.
4310 // ObjC GC and lifetime qualifiers aren't important.
4311 Qualifiers T1Quals = T1.getQualifiers();
4312 Qualifiers T2Quals = T2.getQualifiers();
4313 T1Quals.removeObjCGCAttr();
4314 T1Quals.removeObjCLifetime();
4315 T2Quals.removeObjCGCAttr();
4316 T2Quals.removeObjCLifetime();
4317 if (!T1Quals.compatiblyIncludes(T2Quals))
4318 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004319 }
4320
4321 // If at least one of the types is a class type, the types are not
4322 // related, and we aren't allowed any user conversions, the
4323 // reference binding fails. This case is important for breaking
4324 // recursion, since TryImplicitConversion below will attempt to
4325 // create a temporary through the use of a copy constructor.
4326 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4327 (T1->isRecordType() || T2->isRecordType()))
4328 return ICS;
4329
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004330 // If T1 is reference-related to T2 and the reference is an rvalue
4331 // reference, the initializer expression shall not be an lvalue.
4332 if (RefRelationship >= Sema::Ref_Related &&
4333 isRValRef && Init->Classify(S.Context).isLValue())
4334 return ICS;
4335
Douglas Gregorabe183d2010-04-13 16:31:36 +00004336 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00004337 // When a parameter of reference type is not bound directly to
4338 // an argument expression, the conversion sequence is the one
4339 // required to convert the argument expression to the
4340 // underlying type of the reference according to
4341 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4342 // to copy-initializing a temporary of the underlying type with
4343 // the argument expression. Any difference in top-level
4344 // cv-qualification is subsumed by the initialization itself
4345 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00004346 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4347 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004348 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004349 /*CStyle=*/false,
4350 /*AllowObjCWritebackConversion=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004351
4352 // Of course, that's still a reference binding.
4353 if (ICS.isStandard()) {
4354 ICS.Standard.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004355 ICS.Standard.IsLvalueReference = !isRValRef;
4356 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4357 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004358 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004359 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004360 } else if (ICS.isUserDefined()) {
Douglas Gregor203050c2011-10-04 23:59:32 +00004361 // Don't allow rvalue references to bind to lvalues.
4362 if (DeclType->isRValueReferenceType()) {
4363 if (const ReferenceType *RefType
4364 = ICS.UserDefined.ConversionFunction->getResultType()
4365 ->getAs<LValueReferenceType>()) {
4366 if (!RefType->getPointeeType()->isFunctionType()) {
4367 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4368 DeclType);
4369 return ICS;
4370 }
4371 }
4372 }
4373
Douglas Gregorabe183d2010-04-13 16:31:36 +00004374 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregorf20d2722011-08-15 13:59:46 +00004375 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4376 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4377 ICS.UserDefined.After.BindsToRvalue = true;
4378 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4379 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004380 }
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004381
Douglas Gregorabe183d2010-04-13 16:31:36 +00004382 return ICS;
4383}
4384
Sebastian Redl5405b812011-10-16 18:19:34 +00004385static ImplicitConversionSequence
4386TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4387 bool SuppressUserConversions,
4388 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004389 bool AllowObjCWritebackConversion,
4390 bool AllowExplicit = false);
Sebastian Redl5405b812011-10-16 18:19:34 +00004391
4392/// TryListConversion - Try to copy-initialize a value of type ToType from the
4393/// initializer list From.
4394static ImplicitConversionSequence
4395TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4396 bool SuppressUserConversions,
4397 bool InOverloadResolution,
4398 bool AllowObjCWritebackConversion) {
4399 // C++11 [over.ics.list]p1:
4400 // When an argument is an initializer list, it is not an expression and
4401 // special rules apply for converting it to a parameter type.
4402
4403 ImplicitConversionSequence Result;
4404 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4405
Sebastian Redlb832f6d2012-01-23 22:09:39 +00004406 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redlfe592282012-01-17 22:49:48 +00004407 // initialized from init lists.
Douglas Gregord10099e2012-05-04 16:32:21 +00004408 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redlfe592282012-01-17 22:49:48 +00004409 return Result;
4410
Sebastian Redl5405b812011-10-16 18:19:34 +00004411 // C++11 [over.ics.list]p2:
4412 // If the parameter type is std::initializer_list<X> or "array of X" and
4413 // all the elements can be implicitly converted to X, the implicit
4414 // conversion sequence is the worst conversion necessary to convert an
4415 // element of the list to X.
Sebastian Redladfb5352012-02-27 22:38:26 +00004416 bool toStdInitializerList = false;
Sebastian Redlfe592282012-01-17 22:49:48 +00004417 QualType X;
Sebastian Redl5405b812011-10-16 18:19:34 +00004418 if (ToType->isArrayType())
Richard Smith2801d9a2012-12-09 06:48:56 +00004419 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redlfe592282012-01-17 22:49:48 +00004420 else
Sebastian Redladfb5352012-02-27 22:38:26 +00004421 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redlfe592282012-01-17 22:49:48 +00004422 if (!X.isNull()) {
4423 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4424 Expr *Init = From->getInit(i);
4425 ImplicitConversionSequence ICS =
4426 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4427 InOverloadResolution,
4428 AllowObjCWritebackConversion);
4429 // If a single element isn't convertible, fail.
4430 if (ICS.isBad()) {
4431 Result = ICS;
4432 break;
4433 }
4434 // Otherwise, look for the worst conversion.
4435 if (Result.isBad() ||
4436 CompareImplicitConversionSequences(S, ICS, Result) ==
4437 ImplicitConversionSequence::Worse)
4438 Result = ICS;
4439 }
Douglas Gregor5b4bf132012-04-04 23:09:20 +00004440
4441 // For an empty list, we won't have computed any conversion sequence.
4442 // Introduce the identity conversion sequence.
4443 if (From->getNumInits() == 0) {
4444 Result.setStandard();
4445 Result.Standard.setAsIdentityConversion();
4446 Result.Standard.setFromType(ToType);
4447 Result.Standard.setAllToTypes(ToType);
4448 }
4449
Sebastian Redladfb5352012-02-27 22:38:26 +00004450 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redl5405b812011-10-16 18:19:34 +00004451 return Result;
Sebastian Redlfe592282012-01-17 22:49:48 +00004452 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004453
4454 // C++11 [over.ics.list]p3:
4455 // Otherwise, if the parameter is a non-aggregate class X and overload
4456 // resolution chooses a single best constructor [...] the implicit
4457 // conversion sequence is a user-defined conversion sequence. If multiple
4458 // constructors are viable but none is better than the others, the
4459 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004460 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4461 // This function can deal with initializer lists.
Richard Smith798186a2013-09-06 22:30:28 +00004462 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4463 /*AllowExplicit=*/false,
4464 InOverloadResolution, /*CStyle=*/false,
4465 AllowObjCWritebackConversion);
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004466 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004467
4468 // C++11 [over.ics.list]p4:
4469 // Otherwise, if the parameter has an aggregate type which can be
4470 // initialized from the initializer list [...] the implicit conversion
4471 // sequence is a user-defined conversion sequence.
Sebastian Redl5405b812011-10-16 18:19:34 +00004472 if (ToType->isAggregateType()) {
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004473 // Type is an aggregate, argument is an init list. At this point it comes
4474 // down to checking whether the initialization works.
4475 // FIXME: Find out whether this parameter is consumed or not.
4476 InitializedEntity Entity =
4477 InitializedEntity::InitializeParameter(S.Context, ToType,
4478 /*Consumed=*/false);
4479 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4480 Result.setUserDefined();
4481 Result.UserDefined.Before.setAsIdentityConversion();
4482 // Initializer lists don't have a type.
4483 Result.UserDefined.Before.setFromType(QualType());
4484 Result.UserDefined.Before.setAllToTypes(QualType());
4485
4486 Result.UserDefined.After.setAsIdentityConversion();
4487 Result.UserDefined.After.setFromType(ToType);
4488 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramer83db10e2012-02-02 19:35:29 +00004489 Result.UserDefined.ConversionFunction = 0;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004490 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004491 return Result;
4492 }
4493
4494 // C++11 [over.ics.list]p5:
4495 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004496 if (ToType->isReferenceType()) {
4497 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4498 // mention initializer lists in any way. So we go by what list-
4499 // initialization would do and try to extrapolate from that.
4500
4501 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4502
4503 // If the initializer list has a single element that is reference-related
4504 // to the parameter type, we initialize the reference from that.
4505 if (From->getNumInits() == 1) {
4506 Expr *Init = From->getInit(0);
4507
4508 QualType T2 = Init->getType();
4509
4510 // If the initializer is the address of an overloaded function, try
4511 // to resolve the overloaded function. If all goes well, T2 is the
4512 // type of the resulting function.
4513 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4514 DeclAccessPair Found;
4515 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4516 Init, ToType, false, Found))
4517 T2 = Fn->getType();
4518 }
4519
4520 // Compute some basic properties of the types and the initializer.
4521 bool dummy1 = false;
4522 bool dummy2 = false;
4523 bool dummy3 = false;
4524 Sema::ReferenceCompareResult RefRelationship
4525 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4526 dummy2, dummy3);
4527
Richard Smith3082be22013-09-06 01:22:42 +00004528 if (RefRelationship >= Sema::Ref_Related) {
Richard Smith798186a2013-09-06 22:30:28 +00004529 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4530 SuppressUserConversions,
4531 /*AllowExplicit=*/false);
Richard Smith3082be22013-09-06 01:22:42 +00004532 }
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004533 }
4534
4535 // Otherwise, we bind the reference to a temporary created from the
4536 // initializer list.
4537 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4538 InOverloadResolution,
4539 AllowObjCWritebackConversion);
4540 if (Result.isFailure())
4541 return Result;
4542 assert(!Result.isEllipsis() &&
4543 "Sub-initialization cannot result in ellipsis conversion.");
4544
4545 // Can we even bind to a temporary?
4546 if (ToType->isRValueReferenceType() ||
4547 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4548 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4549 Result.UserDefined.After;
4550 SCS.ReferenceBinding = true;
4551 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4552 SCS.BindsToRvalue = true;
4553 SCS.BindsToFunctionLvalue = false;
4554 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4555 SCS.ObjCLifetimeConversionBinding = false;
4556 } else
4557 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4558 From, ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004559 return Result;
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004560 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004561
4562 // C++11 [over.ics.list]p6:
4563 // Otherwise, if the parameter type is not a class:
4564 if (!ToType->isRecordType()) {
4565 // - if the initializer list has one element, the implicit conversion
4566 // sequence is the one required to convert the element to the
4567 // parameter type.
Sebastian Redl5405b812011-10-16 18:19:34 +00004568 unsigned NumInits = From->getNumInits();
4569 if (NumInits == 1)
4570 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4571 SuppressUserConversions,
4572 InOverloadResolution,
4573 AllowObjCWritebackConversion);
4574 // - if the initializer list has no elements, the implicit conversion
4575 // sequence is the identity conversion.
4576 else if (NumInits == 0) {
4577 Result.setStandard();
4578 Result.Standard.setAsIdentityConversion();
John McCalle14ba2c2012-04-04 02:40:27 +00004579 Result.Standard.setFromType(ToType);
4580 Result.Standard.setAllToTypes(ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004581 }
4582 return Result;
4583 }
4584
4585 // C++11 [over.ics.list]p7:
4586 // In all cases other than those enumerated above, no conversion is possible
4587 return Result;
4588}
4589
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004590/// TryCopyInitialization - Try to copy-initialize a value of type
4591/// ToType from the expression From. Return the implicit conversion
4592/// sequence required to pass this argument, which may be a bad
4593/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00004594/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00004595/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00004596static ImplicitConversionSequence
4597TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004598 bool SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004599 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004600 bool AllowObjCWritebackConversion,
4601 bool AllowExplicit) {
Sebastian Redl5405b812011-10-16 18:19:34 +00004602 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4603 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4604 InOverloadResolution,AllowObjCWritebackConversion);
4605
Douglas Gregorabe183d2010-04-13 16:31:36 +00004606 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00004607 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004608 /*FIXME:*/From->getLocStart(),
4609 SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00004610 AllowExplicit);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004611
John McCall120d63c2010-08-24 20:38:10 +00004612 return TryImplicitConversion(S, From, ToType,
4613 SuppressUserConversions,
4614 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004615 InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00004616 /*CStyle=*/false,
4617 AllowObjCWritebackConversion);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004618}
4619
Anna Zaksf3546ee2011-07-28 19:46:48 +00004620static bool TryCopyInitialization(const CanQualType FromQTy,
4621 const CanQualType ToQTy,
4622 Sema &S,
4623 SourceLocation Loc,
4624 ExprValueKind FromVK) {
4625 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4626 ImplicitConversionSequence ICS =
4627 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4628
4629 return !ICS.isBad();
4630}
4631
Douglas Gregor96176b32008-11-18 23:14:02 +00004632/// TryObjectArgumentInitialization - Try to initialize the object
4633/// parameter of the given member function (@c Method) from the
4634/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00004635static ImplicitConversionSequence
Richard Smith98bfbf52013-01-26 02:07:32 +00004636TryObjectArgumentInitialization(Sema &S, QualType FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004637 Expr::Classification FromClassification,
John McCall120d63c2010-08-24 20:38:10 +00004638 CXXMethodDecl *Method,
4639 CXXRecordDecl *ActingContext) {
4640 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00004641 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4642 // const volatile object.
4643 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4644 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00004645 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00004646
4647 // Set up the conversion sequence as a "bad" conversion, to allow us
4648 // to exit early.
4649 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00004650
4651 // We need to have an object of class type.
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004652 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004653 FromType = PT->getPointeeType();
4654
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004655 // When we had a pointer, it's implicitly dereferenced, so we
4656 // better have an lvalue.
4657 assert(FromClassification.isLValue());
4658 }
4659
Anders Carlssona552f7c2009-05-01 18:34:30 +00004660 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00004661
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004662 // C++0x [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004663 // For non-static member functions, the type of the implicit object
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004664 // parameter is
4665 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004666 // - "lvalue reference to cv X" for functions declared without a
4667 // ref-qualifier or with the & ref-qualifier
4668 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004669 // ref-qualifier
4670 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004671 // where X is the class of which the function is a member and cv is the
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004672 // cv-qualification on the member function declaration.
4673 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004674 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004675 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00004676 // (C++ [over.match.funcs]p5). We perform a simplified version of
4677 // reference binding here, that allows class rvalues to bind to
4678 // non-constant references.
4679
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004680 // First check the qualifiers.
John McCall120d63c2010-08-24 20:38:10 +00004681 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004682 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregora4923eb2009-11-16 21:35:15 +00004683 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00004684 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00004685 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith98bfbf52013-01-26 02:07:32 +00004686 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004687 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004688 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004689
4690 // Check that we have either the same type or a derived type. It
4691 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00004692 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00004693 ImplicitConversionKind SecondKind;
4694 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4695 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00004696 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00004697 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00004698 else {
John McCallb1bdc622010-02-25 01:37:24 +00004699 ICS.setBad(BadConversionSequence::unrelated_class,
4700 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004701 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004702 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004703
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004704 // Check the ref-qualifier.
4705 switch (Method->getRefQualifier()) {
4706 case RQ_None:
4707 // Do nothing; we don't care about lvalueness or rvalueness.
4708 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004709
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004710 case RQ_LValue:
4711 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4712 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004713 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004714 ImplicitParamType);
4715 return ICS;
4716 }
4717 break;
4718
4719 case RQ_RValue:
4720 if (!FromClassification.isRValue()) {
4721 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004722 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004723 ImplicitParamType);
4724 return ICS;
4725 }
4726 break;
4727 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004728
Douglas Gregor96176b32008-11-18 23:14:02 +00004729 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004730 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00004731 ICS.Standard.setAsIdentityConversion();
4732 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00004733 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004734 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004735 ICS.Standard.ReferenceBinding = true;
4736 ICS.Standard.DirectBinding = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004737 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregor440a4832011-01-26 14:52:12 +00004738 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004739 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4740 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4741 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor96176b32008-11-18 23:14:02 +00004742 return ICS;
4743}
4744
4745/// PerformObjectArgumentInitialization - Perform initialization of
4746/// the implicit object parameter for the given Method with the given
4747/// expression.
John Wiegley429bb272011-04-08 18:41:53 +00004748ExprResult
4749Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004750 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00004751 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00004752 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004753 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00004754 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00004755 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004756
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004757 Expr::Classification FromClassification;
Ted Kremenek6217b802009-07-29 21:53:49 +00004758 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004759 FromRecordType = PT->getPointeeType();
4760 DestType = Method->getThisType(Context);
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004761 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004762 } else {
4763 FromRecordType = From->getType();
4764 DestType = ImplicitParamRecordType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004765 FromClassification = From->Classify(Context);
Anders Carlssona552f7c2009-05-01 18:34:30 +00004766 }
4767
John McCall701c89e2009-12-03 04:06:58 +00004768 // Note that we always use the true parent context when performing
4769 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004770 ImplicitConversionSequence ICS
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004771 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4772 Method, Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004773 if (ICS.isBad()) {
4774 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4775 Qualifiers FromQs = FromRecordType.getQualifiers();
4776 Qualifiers ToQs = DestType.getQualifiers();
4777 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4778 if (CVR) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004779 Diag(From->getLocStart(),
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004780 diag::err_member_function_call_bad_cvr)
4781 << Method->getDeclName() << FromRecordType << (CVR - 1)
4782 << From->getSourceRange();
4783 Diag(Method->getLocation(), diag::note_previous_decl)
4784 << Method->getDeclName();
John Wiegley429bb272011-04-08 18:41:53 +00004785 return ExprError();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004786 }
4787 }
4788
Daniel Dunbar96a00142012-03-09 18:35:03 +00004789 return Diag(From->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004790 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00004791 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004792 }
Mike Stump1eb44332009-09-09 15:08:12 +00004793
John Wiegley429bb272011-04-08 18:41:53 +00004794 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4795 ExprResult FromRes =
4796 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4797 if (FromRes.isInvalid())
4798 return ExprError();
4799 From = FromRes.take();
4800 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004801
Douglas Gregor5fccd362010-03-03 23:55:11 +00004802 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley429bb272011-04-08 18:41:53 +00004803 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smithacdfa4d2011-11-10 23:32:36 +00004804 From->getValueKind()).take();
John Wiegley429bb272011-04-08 18:41:53 +00004805 return Owned(From);
Douglas Gregor96176b32008-11-18 23:14:02 +00004806}
4807
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004808/// TryContextuallyConvertToBool - Attempt to contextually convert the
4809/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00004810static ImplicitConversionSequence
4811TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00004812 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00004813 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004814 // FIXME: Are these flags correct?
4815 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00004816 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004817 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004818 /*CStyle=*/false,
4819 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004820}
4821
4822/// PerformContextuallyConvertToBool - Perform a contextual conversion
4823/// of the expression From to bool (C++0x [conv]p3).
John Wiegley429bb272011-04-08 18:41:53 +00004824ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004825 if (checkPlaceholderForOverload(*this, From))
4826 return ExprError();
4827
John McCall120d63c2010-08-24 20:38:10 +00004828 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00004829 if (!ICS.isBad())
4830 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004831
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00004832 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004833 return Diag(From->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +00004834 diag::err_typecheck_bool_condition)
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00004835 << From->getType() << From->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004836 return ExprError();
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004837}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004838
Richard Smith8ef7b202012-01-18 23:55:52 +00004839/// Check that the specified conversion is permitted in a converted constant
4840/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4841/// is acceptable.
4842static bool CheckConvertedConstantConversions(Sema &S,
4843 StandardConversionSequence &SCS) {
4844 // Since we know that the target type is an integral or unscoped enumeration
4845 // type, most conversion kinds are impossible. All possible First and Third
4846 // conversions are fine.
4847 switch (SCS.Second) {
4848 case ICK_Identity:
4849 case ICK_Integral_Promotion:
4850 case ICK_Integral_Conversion:
Guy Benyei6959acd2013-02-07 16:05:33 +00004851 case ICK_Zero_Event_Conversion:
Richard Smith8ef7b202012-01-18 23:55:52 +00004852 return true;
4853
4854 case ICK_Boolean_Conversion:
Richard Smith2bcb9842012-09-13 22:00:12 +00004855 // Conversion from an integral or unscoped enumeration type to bool is
4856 // classified as ICK_Boolean_Conversion, but it's also an integral
4857 // conversion, so it's permitted in a converted constant expression.
4858 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4859 SCS.getToType(2)->isBooleanType();
4860
Richard Smith8ef7b202012-01-18 23:55:52 +00004861 case ICK_Floating_Integral:
4862 case ICK_Complex_Real:
4863 return false;
4864
4865 case ICK_Lvalue_To_Rvalue:
4866 case ICK_Array_To_Pointer:
4867 case ICK_Function_To_Pointer:
4868 case ICK_NoReturn_Adjustment:
4869 case ICK_Qualification:
4870 case ICK_Compatible_Conversion:
4871 case ICK_Vector_Conversion:
4872 case ICK_Vector_Splat:
4873 case ICK_Derived_To_Base:
4874 case ICK_Pointer_Conversion:
4875 case ICK_Pointer_Member:
4876 case ICK_Block_Pointer_Conversion:
4877 case ICK_Writeback_Conversion:
4878 case ICK_Floating_Promotion:
4879 case ICK_Complex_Promotion:
4880 case ICK_Complex_Conversion:
4881 case ICK_Floating_Conversion:
4882 case ICK_TransparentUnionConversion:
4883 llvm_unreachable("unexpected second conversion kind");
4884
4885 case ICK_Num_Conversion_Kinds:
4886 break;
4887 }
4888
4889 llvm_unreachable("unknown conversion kind");
4890}
4891
4892/// CheckConvertedConstantExpression - Check that the expression From is a
4893/// converted constant expression of type T, perform the conversion and produce
4894/// the converted expression, per C++11 [expr.const]p3.
4895ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4896 llvm::APSInt &Value,
4897 CCEKind CCE) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004898 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
Richard Smith8ef7b202012-01-18 23:55:52 +00004899 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4900
4901 if (checkPlaceholderForOverload(*this, From))
4902 return ExprError();
4903
4904 // C++11 [expr.const]p3 with proposed wording fixes:
4905 // A converted constant expression of type T is a core constant expression,
4906 // implicitly converted to a prvalue of type T, where the converted
4907 // expression is a literal constant expression and the implicit conversion
4908 // sequence contains only user-defined conversions, lvalue-to-rvalue
4909 // conversions, integral promotions, and integral conversions other than
4910 // narrowing conversions.
4911 ImplicitConversionSequence ICS =
4912 TryImplicitConversion(From, T,
4913 /*SuppressUserConversions=*/false,
4914 /*AllowExplicit=*/false,
4915 /*InOverloadResolution=*/false,
4916 /*CStyle=*/false,
4917 /*AllowObjcWritebackConversion=*/false);
4918 StandardConversionSequence *SCS = 0;
4919 switch (ICS.getKind()) {
4920 case ImplicitConversionSequence::StandardConversion:
4921 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004922 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004923 diag::err_typecheck_converted_constant_expression_disallowed)
4924 << From->getType() << From->getSourceRange() << T;
4925 SCS = &ICS.Standard;
4926 break;
4927 case ImplicitConversionSequence::UserDefinedConversion:
4928 // We are converting from class type to an integral or enumeration type, so
4929 // the Before sequence must be trivial.
4930 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004931 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004932 diag::err_typecheck_converted_constant_expression_disallowed)
4933 << From->getType() << From->getSourceRange() << T;
4934 SCS = &ICS.UserDefined.After;
4935 break;
4936 case ImplicitConversionSequence::AmbiguousConversion:
4937 case ImplicitConversionSequence::BadConversion:
4938 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004939 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004940 diag::err_typecheck_converted_constant_expression)
4941 << From->getType() << From->getSourceRange() << T;
4942 return ExprError();
4943
4944 case ImplicitConversionSequence::EllipsisConversion:
4945 llvm_unreachable("ellipsis conversion in converted constant expression");
4946 }
4947
4948 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4949 if (Result.isInvalid())
4950 return Result;
4951
4952 // Check for a narrowing implicit conversion.
4953 APValue PreNarrowingValue;
Richard Smithf6028062012-03-23 23:55:39 +00004954 QualType PreNarrowingType;
Richard Smithf6028062012-03-23 23:55:39 +00004955 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4956 PreNarrowingType)) {
Richard Smith8ef7b202012-01-18 23:55:52 +00004957 case NK_Variable_Narrowing:
4958 // Implicit conversion to a narrower type, and the value is not a constant
4959 // expression. We'll diagnose this in a moment.
4960 case NK_Not_Narrowing:
4961 break;
4962
4963 case NK_Constant_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004964 Diag(From->getLocStart(),
4965 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4966 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004967 << CCE << /*Constant*/1
Richard Smithf6028062012-03-23 23:55:39 +00004968 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smith8ef7b202012-01-18 23:55:52 +00004969 break;
4970
4971 case NK_Type_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004972 Diag(From->getLocStart(),
4973 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4974 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004975 << CCE << /*Constant*/0 << From->getType() << T;
4976 break;
4977 }
4978
4979 // Check the expression is a constant expression.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00004980 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith8ef7b202012-01-18 23:55:52 +00004981 Expr::EvalResult Eval;
4982 Eval.Diag = &Notes;
4983
Douglas Gregor484f6fa2013-04-08 23:24:07 +00004984 if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) {
Richard Smith8ef7b202012-01-18 23:55:52 +00004985 // The expression can't be folded, so we can't keep it at this position in
4986 // the AST.
4987 Result = ExprError();
Richard Smithf72fccf2012-01-30 22:27:01 +00004988 } else {
Richard Smith8ef7b202012-01-18 23:55:52 +00004989 Value = Eval.Val.getInt();
Richard Smithf72fccf2012-01-30 22:27:01 +00004990
4991 if (Notes.empty()) {
4992 // It's a constant expression.
4993 return Result;
4994 }
Richard Smith8ef7b202012-01-18 23:55:52 +00004995 }
4996
4997 // It's not a constant expression. Produce an appropriate diagnostic.
4998 if (Notes.size() == 1 &&
4999 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5000 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5001 else {
Daniel Dunbar96a00142012-03-09 18:35:03 +00005002 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smith8ef7b202012-01-18 23:55:52 +00005003 << CCE << From->getSourceRange();
5004 for (unsigned I = 0; I < Notes.size(); ++I)
5005 Diag(Notes[I].first, Notes[I].second);
5006 }
Richard Smithf72fccf2012-01-30 22:27:01 +00005007 return Result;
Richard Smith8ef7b202012-01-18 23:55:52 +00005008}
5009
John McCall0bcc9bc2011-09-09 06:11:02 +00005010/// dropPointerConversions - If the given standard conversion sequence
5011/// involves any pointer conversions, remove them. This may change
5012/// the result type of the conversion sequence.
5013static void dropPointerConversion(StandardConversionSequence &SCS) {
5014 if (SCS.Second == ICK_Pointer_Conversion) {
5015 SCS.Second = ICK_Identity;
5016 SCS.Third = ICK_Identity;
5017 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5018 }
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005019}
John McCall120d63c2010-08-24 20:38:10 +00005020
John McCall0bcc9bc2011-09-09 06:11:02 +00005021/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5022/// convert the expression From to an Objective-C pointer type.
5023static ImplicitConversionSequence
5024TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5025 // Do an implicit conversion to 'id'.
5026 QualType Ty = S.Context.getObjCIdType();
5027 ImplicitConversionSequence ICS
5028 = TryImplicitConversion(S, From, Ty,
5029 // FIXME: Are these flags correct?
5030 /*SuppressUserConversions=*/false,
5031 /*AllowExplicit=*/true,
5032 /*InOverloadResolution=*/false,
5033 /*CStyle=*/false,
5034 /*AllowObjCWritebackConversion=*/false);
5035
5036 // Strip off any final conversions to 'id'.
5037 switch (ICS.getKind()) {
5038 case ImplicitConversionSequence::BadConversion:
5039 case ImplicitConversionSequence::AmbiguousConversion:
5040 case ImplicitConversionSequence::EllipsisConversion:
5041 break;
5042
5043 case ImplicitConversionSequence::UserDefinedConversion:
5044 dropPointerConversion(ICS.UserDefined.After);
5045 break;
5046
5047 case ImplicitConversionSequence::StandardConversion:
5048 dropPointerConversion(ICS.Standard);
5049 break;
5050 }
5051
5052 return ICS;
5053}
5054
5055/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5056/// conversion of the expression From to an Objective-C pointer type.
5057ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00005058 if (checkPlaceholderForOverload(*this, From))
5059 return ExprError();
5060
John McCallc12c5bb2010-05-15 11:32:37 +00005061 QualType Ty = Context.getObjCIdType();
John McCall0bcc9bc2011-09-09 06:11:02 +00005062 ImplicitConversionSequence ICS =
5063 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005064 if (!ICS.isBad())
5065 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley429bb272011-04-08 18:41:53 +00005066 return ExprError();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005067}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005068
Richard Smithf39aec12012-02-04 07:07:42 +00005069/// Determine whether the provided type is an integral type, or an enumeration
5070/// type of a permitted flavor.
Richard Smith097e0a22013-05-21 19:05:48 +00005071bool Sema::ICEConvertDiagnoser::match(QualType T) {
5072 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5073 : T->isIntegralOrUnscopedEnumerationType();
Richard Smithf39aec12012-02-04 07:07:42 +00005074}
5075
Larisse Voufo50b60b32013-06-10 06:50:24 +00005076static ExprResult
5077diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5078 Sema::ContextualImplicitConverter &Converter,
5079 QualType T, UnresolvedSetImpl &ViableConversions) {
5080
5081 if (Converter.Suppress)
5082 return ExprError();
5083
5084 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5085 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5086 CXXConversionDecl *Conv =
5087 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5088 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5089 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5090 }
5091 return SemaRef.Owned(From);
5092}
5093
5094static bool
5095diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5096 Sema::ContextualImplicitConverter &Converter,
5097 QualType T, bool HadMultipleCandidates,
5098 UnresolvedSetImpl &ExplicitConversions) {
5099 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5100 DeclAccessPair Found = ExplicitConversions[0];
5101 CXXConversionDecl *Conversion =
5102 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5103
5104 // The user probably meant to invoke the given explicit
5105 // conversion; use it.
5106 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5107 std::string TypeStr;
5108 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5109
5110 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5111 << FixItHint::CreateInsertion(From->getLocStart(),
5112 "static_cast<" + TypeStr + ">(")
5113 << FixItHint::CreateInsertion(
5114 SemaRef.PP.getLocForEndOfToken(From->getLocEnd()), ")");
5115 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5116
5117 // If we aren't in a SFINAE context, build a call to the
5118 // explicit conversion function.
5119 if (SemaRef.isSFINAEContext())
5120 return true;
5121
5122 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5123 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5124 HadMultipleCandidates);
5125 if (Result.isInvalid())
5126 return true;
5127 // Record usage of conversion in an implicit cast.
5128 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5129 CK_UserDefinedConversion, Result.get(), 0,
5130 Result.get()->getValueKind());
5131 }
5132 return false;
5133}
5134
5135static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5136 Sema::ContextualImplicitConverter &Converter,
5137 QualType T, bool HadMultipleCandidates,
5138 DeclAccessPair &Found) {
5139 CXXConversionDecl *Conversion =
5140 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5141 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5142
5143 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5144 if (!Converter.SuppressConversion) {
5145 if (SemaRef.isSFINAEContext())
5146 return true;
5147
5148 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5149 << From->getSourceRange();
5150 }
5151
5152 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5153 HadMultipleCandidates);
5154 if (Result.isInvalid())
5155 return true;
5156 // Record usage of conversion in an implicit cast.
5157 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5158 CK_UserDefinedConversion, Result.get(), 0,
5159 Result.get()->getValueKind());
5160 return false;
5161}
5162
5163static ExprResult finishContextualImplicitConversion(
5164 Sema &SemaRef, SourceLocation Loc, Expr *From,
5165 Sema::ContextualImplicitConverter &Converter) {
5166 if (!Converter.match(From->getType()) && !Converter.Suppress)
5167 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5168 << From->getSourceRange();
5169
5170 return SemaRef.DefaultLvalueConversion(From);
5171}
5172
5173static void
5174collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5175 UnresolvedSetImpl &ViableConversions,
5176 OverloadCandidateSet &CandidateSet) {
5177 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5178 DeclAccessPair FoundDecl = ViableConversions[I];
5179 NamedDecl *D = FoundDecl.getDecl();
5180 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5181 if (isa<UsingShadowDecl>(D))
5182 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5183
5184 CXXConversionDecl *Conv;
5185 FunctionTemplateDecl *ConvTemplate;
5186 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5187 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5188 else
5189 Conv = cast<CXXConversionDecl>(D);
5190
5191 if (ConvTemplate)
5192 SemaRef.AddTemplateConversionCandidate(
5193 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet);
5194 else
5195 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5196 ToType, CandidateSet);
5197 }
5198}
5199
Richard Smith097e0a22013-05-21 19:05:48 +00005200/// \brief Attempt to convert the given expression to a type which is accepted
5201/// by the given converter.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005202///
Richard Smith097e0a22013-05-21 19:05:48 +00005203/// This routine will attempt to convert an expression of class type to a
5204/// type accepted by the specified converter. In C++11 and before, the class
5205/// must have a single non-explicit conversion function converting to a matching
5206/// type. In C++1y, there can be multiple such conversion functions, but only
5207/// one target type.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005208///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005209/// \param Loc The source location of the construct that requires the
5210/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005211///
James Dennett40ae6662012-06-22 08:52:37 +00005212/// \param From The expression we're converting from.
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005213///
Richard Smith097e0a22013-05-21 19:05:48 +00005214/// \param Converter Used to control and diagnose the conversion process.
Richard Smithf39aec12012-02-04 07:07:42 +00005215///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005216/// \returns The expression, converted to an integral or enumeration type if
5217/// successful.
Richard Smith097e0a22013-05-21 19:05:48 +00005218ExprResult Sema::PerformContextualImplicitConversion(
5219 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005220 // We can't perform any more checking for type-dependent expressions.
5221 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00005222 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005223
Eli Friedmanceccab92012-01-26 00:26:18 +00005224 // Process placeholders immediately.
5225 if (From->hasPlaceholderType()) {
5226 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo50b60b32013-06-10 06:50:24 +00005227 if (result.isInvalid())
5228 return result;
Eli Friedmanceccab92012-01-26 00:26:18 +00005229 From = result.take();
5230 }
5231
Richard Smith097e0a22013-05-21 19:05:48 +00005232 // If the expression already has a matching type, we're golden.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005233 QualType T = From->getType();
Richard Smith097e0a22013-05-21 19:05:48 +00005234 if (Converter.match(T))
Eli Friedmanceccab92012-01-26 00:26:18 +00005235 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005236
5237 // FIXME: Check for missing '()' if T is a function type?
5238
Richard Smith097e0a22013-05-21 19:05:48 +00005239 // We can only perform contextual implicit conversions on objects of class
5240 // type.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005241 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikie4e4d0842012-03-11 07:00:24 +00005242 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smith097e0a22013-05-21 19:05:48 +00005243 if (!Converter.Suppress)
5244 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00005245 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005246 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005247
Douglas Gregorc30614b2010-06-29 23:17:37 +00005248 // We must have a complete class type.
Douglas Gregorf502d8e2012-05-04 16:48:41 +00005249 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smith097e0a22013-05-21 19:05:48 +00005250 ContextualImplicitConverter &Converter;
Douglas Gregorab41fe92012-05-04 22:38:52 +00005251 Expr *From;
Richard Smith097e0a22013-05-21 19:05:48 +00005252
5253 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5254 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5255
Douglas Gregord10099e2012-05-04 16:32:21 +00005256 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Richard Smith097e0a22013-05-21 19:05:48 +00005257 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregord10099e2012-05-04 16:32:21 +00005258 }
Richard Smith097e0a22013-05-21 19:05:48 +00005259 } IncompleteDiagnoser(Converter, From);
Douglas Gregord10099e2012-05-04 16:32:21 +00005260
5261 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCall9ae2f072010-08-23 23:25:46 +00005262 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005263
Douglas Gregorc30614b2010-06-29 23:17:37 +00005264 // Look for a conversion to an integral or enumeration type.
Larisse Voufo50b60b32013-06-10 06:50:24 +00005265 UnresolvedSet<4>
5266 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005267 UnresolvedSet<4> ExplicitConversions;
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00005268 std::pair<CXXRecordDecl::conversion_iterator,
Larisse Voufo50b60b32013-06-10 06:50:24 +00005269 CXXRecordDecl::conversion_iterator> Conversions =
5270 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005271
Larisse Voufo50b60b32013-06-10 06:50:24 +00005272 bool HadMultipleCandidates =
5273 (std::distance(Conversions.first, Conversions.second) > 1);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005274
Larisse Voufo50b60b32013-06-10 06:50:24 +00005275 // To check that there is only one target type, in C++1y:
5276 QualType ToType;
5277 bool HasUniqueTargetType = true;
5278
5279 // Collect explicit or viable (potentially in C++1y) conversions.
5280 for (CXXRecordDecl::conversion_iterator I = Conversions.first,
5281 E = Conversions.second;
5282 I != E; ++I) {
5283 NamedDecl *D = (*I)->getUnderlyingDecl();
5284 CXXConversionDecl *Conversion;
5285 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5286 if (ConvTemplate) {
5287 if (getLangOpts().CPlusPlus1y)
5288 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5289 else
5290 continue; // C++11 does not consider conversion operator templates(?).
5291 } else
5292 Conversion = cast<CXXConversionDecl>(D);
5293
5294 assert((!ConvTemplate || getLangOpts().CPlusPlus1y) &&
5295 "Conversion operator templates are considered potentially "
5296 "viable in C++1y");
5297
5298 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5299 if (Converter.match(CurToType) || ConvTemplate) {
5300
5301 if (Conversion->isExplicit()) {
5302 // FIXME: For C++1y, do we need this restriction?
5303 // cf. diagnoseNoViableConversion()
5304 if (!ConvTemplate)
Douglas Gregorc30614b2010-06-29 23:17:37 +00005305 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo50b60b32013-06-10 06:50:24 +00005306 } else {
5307 if (!ConvTemplate && getLangOpts().CPlusPlus1y) {
5308 if (ToType.isNull())
5309 ToType = CurToType.getUnqualifiedType();
5310 else if (HasUniqueTargetType &&
5311 (CurToType.getUnqualifiedType() != ToType))
5312 HasUniqueTargetType = false;
5313 }
5314 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005315 }
Richard Smithf39aec12012-02-04 07:07:42 +00005316 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005317 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005318
Larisse Voufo50b60b32013-06-10 06:50:24 +00005319 if (getLangOpts().CPlusPlus1y) {
5320 // C++1y [conv]p6:
5321 // ... An expression e of class type E appearing in such a context
5322 // is said to be contextually implicitly converted to a specified
5323 // type T and is well-formed if and only if e can be implicitly
5324 // converted to a type T that is determined as follows: E is searched
Larisse Voufo7acc5a62013-06-10 08:25:58 +00005325 // for conversion functions whose return type is cv T or reference to
5326 // cv T such that T is allowed by the context. There shall be
Larisse Voufo50b60b32013-06-10 06:50:24 +00005327 // exactly one such T.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005328
Larisse Voufo50b60b32013-06-10 06:50:24 +00005329 // If no unique T is found:
5330 if (ToType.isNull()) {
5331 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5332 HadMultipleCandidates,
5333 ExplicitConversions))
Douglas Gregorc30614b2010-06-29 23:17:37 +00005334 return ExprError();
Larisse Voufo50b60b32013-06-10 06:50:24 +00005335 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005336 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005337
Larisse Voufo50b60b32013-06-10 06:50:24 +00005338 // If more than one unique Ts are found:
5339 if (!HasUniqueTargetType)
5340 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5341 ViableConversions);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005342
Larisse Voufo50b60b32013-06-10 06:50:24 +00005343 // If one unique T is found:
5344 // First, build a candidate set from the previously recorded
5345 // potentially viable conversions.
5346 OverloadCandidateSet CandidateSet(Loc);
5347 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5348 CandidateSet);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005349
Larisse Voufo50b60b32013-06-10 06:50:24 +00005350 // Then, perform overload resolution over the candidate set.
5351 OverloadCandidateSet::iterator Best;
5352 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5353 case OR_Success: {
5354 // Apply this conversion.
5355 DeclAccessPair Found =
5356 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5357 if (recordConversion(*this, Loc, From, Converter, T,
5358 HadMultipleCandidates, Found))
5359 return ExprError();
5360 break;
5361 }
5362 case OR_Ambiguous:
5363 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5364 ViableConversions);
5365 case OR_No_Viable_Function:
5366 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5367 HadMultipleCandidates,
5368 ExplicitConversions))
5369 return ExprError();
5370 // fall through 'OR_Deleted' case.
5371 case OR_Deleted:
5372 // We'll complain below about a non-integral condition type.
5373 break;
5374 }
5375 } else {
5376 switch (ViableConversions.size()) {
5377 case 0: {
5378 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5379 HadMultipleCandidates,
5380 ExplicitConversions))
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005381 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005382
Larisse Voufo50b60b32013-06-10 06:50:24 +00005383 // We'll complain below about a non-integral condition type.
5384 break;
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005385 }
Larisse Voufo50b60b32013-06-10 06:50:24 +00005386 case 1: {
5387 // Apply this conversion.
5388 DeclAccessPair Found = ViableConversions[0];
5389 if (recordConversion(*this, Loc, From, Converter, T,
5390 HadMultipleCandidates, Found))
5391 return ExprError();
5392 break;
5393 }
5394 default:
5395 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5396 ViableConversions);
5397 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005398 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005399
Larisse Voufo50b60b32013-06-10 06:50:24 +00005400 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005401}
5402
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005403/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00005404/// candidate functions, using the given function call arguments. If
5405/// @p SuppressUserConversions, then don't allow user-defined
5406/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005407///
James Dennett699c9042012-06-15 07:13:21 +00005408/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005409/// based on an incomplete set of function arguments. This feature is used by
5410/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00005411void
5412Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00005413 DeclAccessPair FoundDecl,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005414 ArrayRef<Expr *> Args,
Douglas Gregor225c41e2008-11-03 19:09:14 +00005415 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00005416 bool SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00005417 bool PartialOverloading,
5418 bool AllowExplicit) {
Mike Stump1eb44332009-09-09 15:08:12 +00005419 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005420 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005421 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00005422 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi00995302011-01-27 07:09:49 +00005423 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00005424
Douglas Gregor88a35142008-12-22 05:46:06 +00005425 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005426 if (!isa<CXXConstructorDecl>(Method)) {
5427 // If we get here, it's because we're calling a member function
5428 // that is named without a member access expression (e.g.,
5429 // "this->f") that was either written explicitly or created
5430 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00005431 // function, e.g., X::f(). We use an empty type for the implied
5432 // object argument (C++ [over.call.func]p3), and the acting context
5433 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00005434 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005435 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005436 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005437 return;
5438 }
5439 // We treat a constructor like a non-member function, since its object
5440 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00005441 }
5442
Douglas Gregorfd476482009-11-13 23:59:09 +00005443 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00005444 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00005445
Douglas Gregor7edfb692009-11-23 12:27:39 +00005446 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005447 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005448
Douglas Gregor66724ea2009-11-14 01:20:54 +00005449 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5450 // C++ [class.copy]p3:
5451 // A member function template is never instantiated to perform the copy
5452 // of a class object to an object of its class type.
5453 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charles13a140c2012-02-25 11:00:22 +00005454 if (Args.size() == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00005455 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00005456 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5457 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00005458 return;
5459 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005460
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005461 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005462 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCall9aa472c2010-03-19 07:35:19 +00005463 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005464 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00005465 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005466 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005467 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005468 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005469
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005470 unsigned NumArgsInProto = Proto->getNumArgs();
5471
5472 // (C++ 13.3.2p2): A candidate function having fewer than m
5473 // parameters is viable only if it has an ellipsis in its parameter
5474 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005475 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor5bd1a112009-09-23 14:56:09 +00005476 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005477 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005478 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005479 return;
5480 }
5481
5482 // (C++ 13.3.2p2): A candidate function having more than m parameters
5483 // is viable only if the (m+1)st parameter has a default argument
5484 // (8.3.6). For the purposes of overload resolution, the
5485 // parameter list is truncated on the right, so that there are
5486 // exactly m parameters.
5487 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005488 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005489 // Not enough arguments.
5490 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005491 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005492 return;
5493 }
5494
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005495 // (CUDA B.1): Check for invalid calls between targets.
David Blaikie4e4d0842012-03-11 07:00:24 +00005496 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005497 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5498 if (CheckCUDATarget(Caller, Function)) {
5499 Candidate.Viable = false;
5500 Candidate.FailureKind = ovl_fail_bad_target;
5501 return;
5502 }
5503
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005504 // Determine the implicit conversion sequences for each of the
5505 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005506 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005507 if (ArgIdx < NumArgsInProto) {
5508 // (C++ 13.3.2p3): for F to be a viable function, there shall
5509 // exist for each argument an implicit conversion sequence
5510 // (13.3.3.1) that converts that argument to the corresponding
5511 // parameter of F.
5512 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005513 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005514 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005515 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005516 /*InOverloadResolution=*/true,
5517 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005518 getLangOpts().ObjCAutoRefCount,
Douglas Gregored878af2012-02-24 23:56:31 +00005519 AllowExplicit);
John McCall1d318332010-01-12 00:44:57 +00005520 if (Candidate.Conversions[ArgIdx].isBad()) {
5521 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005522 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00005523 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00005524 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005525 } else {
5526 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5527 // argument for which there is no corresponding parameter is
5528 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005529 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005530 }
5531 }
5532}
5533
Douglas Gregor063daf62009-03-13 18:40:31 +00005534/// \brief Add all of the function declarations in the given function set to
5535/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00005536void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005537 ArrayRef<Expr *> Args,
Douglas Gregor063daf62009-03-13 18:40:31 +00005538 OverloadCandidateSet& CandidateSet,
Richard Smith36f5cfe2012-03-09 08:00:36 +00005539 bool SuppressUserConversions,
5540 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall6e266892010-01-26 03:27:55 +00005541 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00005542 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5543 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005544 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005545 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005546 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005547 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005548 Args.slice(1), CandidateSet,
5549 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005550 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00005551 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00005552 SuppressUserConversions);
5553 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005554 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00005555 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5556 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005557 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005558 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005559 ExplicitTemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005560 Args[0]->getType(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005561 Args[0]->Classify(Context), Args.slice(1),
5562 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005563 else
John McCall9aa472c2010-03-19 07:35:19 +00005564 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005565 ExplicitTemplateArgs, Args,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005566 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005567 }
Douglas Gregor364e0212009-06-27 21:05:07 +00005568 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005569}
5570
John McCall314be4e2009-11-17 07:50:12 +00005571/// AddMethodCandidate - Adds a named decl (which is some kind of
5572/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00005573void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005574 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005575 Expr::Classification ObjectClassification,
Rafael Espindola548107e2013-04-29 19:29:25 +00005576 ArrayRef<Expr *> Args,
John McCall314be4e2009-11-17 07:50:12 +00005577 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005578 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00005579 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00005580 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00005581
5582 if (isa<UsingShadowDecl>(Decl))
5583 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005584
John McCall314be4e2009-11-17 07:50:12 +00005585 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5586 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5587 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00005588 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5589 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005590 ObjectType, ObjectClassification,
Rafael Espindola548107e2013-04-29 19:29:25 +00005591 Args, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005592 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005593 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005594 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005595 ObjectType, ObjectClassification,
Rafael Espindola548107e2013-04-29 19:29:25 +00005596 Args,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005597 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005598 }
5599}
5600
Douglas Gregor96176b32008-11-18 23:14:02 +00005601/// AddMethodCandidate - Adds the given C++ member function to the set
5602/// of candidate functions, using the given function call arguments
5603/// and the object argument (@c Object). For example, in a call
5604/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5605/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5606/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00005607/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00005608void
John McCall9aa472c2010-03-19 07:35:19 +00005609Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00005610 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005611 Expr::Classification ObjectClassification,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005612 ArrayRef<Expr *> Args,
Douglas Gregor96176b32008-11-18 23:14:02 +00005613 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005614 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00005615 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005616 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00005617 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005618 assert(!isa<CXXConstructorDecl>(Method) &&
5619 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00005620
Douglas Gregor3f396022009-09-28 04:47:19 +00005621 if (!CandidateSet.isNewCandidate(Method))
5622 return;
5623
Douglas Gregor7edfb692009-11-23 12:27:39 +00005624 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005625 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005626
Douglas Gregor96176b32008-11-18 23:14:02 +00005627 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005628 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005629 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00005630 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005631 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005632 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005633 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor96176b32008-11-18 23:14:02 +00005634
5635 unsigned NumArgsInProto = Proto->getNumArgs();
5636
5637 // (C++ 13.3.2p2): A candidate function having fewer than m
5638 // parameters is viable only if it has an ellipsis in its parameter
5639 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005640 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005641 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005642 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005643 return;
5644 }
5645
5646 // (C++ 13.3.2p2): A candidate function having more than m parameters
5647 // is viable only if the (m+1)st parameter has a default argument
5648 // (8.3.6). For the purposes of overload resolution, the
5649 // parameter list is truncated on the right, so that there are
5650 // exactly m parameters.
5651 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005652 if (Args.size() < MinRequiredArgs) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005653 // Not enough arguments.
5654 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005655 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005656 return;
5657 }
5658
5659 Candidate.Viable = true;
Douglas Gregor96176b32008-11-18 23:14:02 +00005660
John McCall701c89e2009-12-03 04:06:58 +00005661 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00005662 // The implicit object argument is ignored.
5663 Candidate.IgnoreObjectArgument = true;
5664 else {
5665 // Determine the implicit conversion sequence for the object
5666 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00005667 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005668 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5669 Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005670 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00005671 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005672 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00005673 return;
5674 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005675 }
5676
5677 // Determine the implicit conversion sequences for each of the
5678 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005679 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005680 if (ArgIdx < NumArgsInProto) {
5681 // (C++ 13.3.2p3): for F to be a viable function, there shall
5682 // exist for each argument an implicit conversion sequence
5683 // (13.3.3.1) that converts that argument to the corresponding
5684 // parameter of F.
5685 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005686 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005687 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005688 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005689 /*InOverloadResolution=*/true,
5690 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005691 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005692 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005693 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005694 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00005695 break;
5696 }
5697 } else {
5698 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5699 // argument for which there is no corresponding parameter is
5700 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005701 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00005702 }
5703 }
5704}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005705
Douglas Gregor6b906862009-08-21 00:16:32 +00005706/// \brief Add a C++ member function template as a candidate to the candidate
5707/// set, using template argument deduction to produce an appropriate member
5708/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005709void
Douglas Gregor6b906862009-08-21 00:16:32 +00005710Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00005711 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005712 CXXRecordDecl *ActingContext,
Douglas Gregor67714232011-03-03 02:41:12 +00005713 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00005714 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005715 Expr::Classification ObjectClassification,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005716 ArrayRef<Expr *> Args,
Douglas Gregor6b906862009-08-21 00:16:32 +00005717 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005718 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005719 if (!CandidateSet.isNewCandidate(MethodTmpl))
5720 return;
5721
Douglas Gregor6b906862009-08-21 00:16:32 +00005722 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005723 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00005724 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005725 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00005726 // candidate functions in the usual way.113) A given name can refer to one
5727 // or more function templates and also to a set of overloaded non-template
5728 // functions. In such a case, the candidate functions generated from each
5729 // function template are combined with the set of non-template candidate
5730 // functions.
Craig Topper93e45992012-09-19 02:26:47 +00005731 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00005732 FunctionDecl *Specialization = 0;
5733 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005734 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5735 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005736 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005737 Candidate.FoundDecl = FoundDecl;
5738 Candidate.Function = MethodTmpl->getTemplatedDecl();
5739 Candidate.Viable = false;
5740 Candidate.FailureKind = ovl_fail_bad_deduction;
5741 Candidate.IsSurrogate = false;
5742 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005743 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005744 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005745 Info);
5746 return;
5747 }
Mike Stump1eb44332009-09-09 15:08:12 +00005748
Douglas Gregor6b906862009-08-21 00:16:32 +00005749 // Add the function template specialization produced by template argument
5750 // deduction as a candidate.
5751 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00005752 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00005753 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00005754 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005755 ActingContext, ObjectType, ObjectClassification, Args,
5756 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00005757}
5758
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005759/// \brief Add a C++ function template specialization as a candidate
5760/// in the candidate set, using template argument deduction to produce
5761/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005762void
Douglas Gregore53060f2009-06-25 22:08:12 +00005763Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005764 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00005765 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005766 ArrayRef<Expr *> Args,
Douglas Gregore53060f2009-06-25 22:08:12 +00005767 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005768 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005769 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5770 return;
5771
Douglas Gregore53060f2009-06-25 22:08:12 +00005772 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005773 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00005774 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005775 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00005776 // candidate functions in the usual way.113) A given name can refer to one
5777 // or more function templates and also to a set of overloaded non-template
5778 // functions. In such a case, the candidate functions generated from each
5779 // function template are combined with the set of non-template candidate
5780 // functions.
Craig Topper93e45992012-09-19 02:26:47 +00005781 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00005782 FunctionDecl *Specialization = 0;
5783 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005784 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5785 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005786 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCall9aa472c2010-03-19 07:35:19 +00005787 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00005788 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5789 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005790 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00005791 Candidate.IsSurrogate = false;
5792 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005793 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005794 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005795 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00005796 return;
5797 }
Mike Stump1eb44332009-09-09 15:08:12 +00005798
Douglas Gregore53060f2009-06-25 22:08:12 +00005799 // Add the function template specialization produced by template argument
5800 // deduction as a candidate.
5801 assert(Specialization && "Missing function template specialization?");
Ahmed Charles13a140c2012-02-25 11:00:22 +00005802 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005803 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00005804}
Mike Stump1eb44332009-09-09 15:08:12 +00005805
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005806/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00005807/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005808/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00005809/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005810/// (which may or may not be the same type as the type that the
5811/// conversion function produces).
5812void
5813Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005814 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005815 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005816 Expr *From, QualType ToType,
5817 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005818 assert(!Conversion->getDescribedFunctionTemplate() &&
5819 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005820 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00005821 if (!CandidateSet.isNewCandidate(Conversion))
5822 return;
5823
Richard Smith60e141e2013-05-04 07:00:32 +00005824 // If the conversion function has an undeduced return type, trigger its
5825 // deduction now.
5826 if (getLangOpts().CPlusPlus1y && ConvType->isUndeducedType()) {
5827 if (DeduceReturnType(Conversion, From->getExprLoc()))
5828 return;
5829 ConvType = Conversion->getConversionType().getNonReferenceType();
5830 }
5831
Douglas Gregor7edfb692009-11-23 12:27:39 +00005832 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005833 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005834
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005835 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005836 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCall9aa472c2010-03-19 07:35:19 +00005837 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005838 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005839 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005840 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005841 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005842 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00005843 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005844 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005845 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005846
Douglas Gregorbca39322010-08-19 15:37:02 +00005847 // C++ [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005848 // For conversion functions, the function is considered to be a member of
5849 // the class of the implicit implied object argument for the purpose of
Douglas Gregorbca39322010-08-19 15:37:02 +00005850 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005851 //
5852 // Determine the implicit conversion sequence for the implicit
5853 // object parameter.
5854 QualType ImplicitParamType = From->getType();
5855 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5856 ImplicitParamType = FromPtrType->getPointeeType();
5857 CXXRecordDecl *ConversionContext
5858 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005859
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005860 Candidate.Conversions[0]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005861 = TryObjectArgumentInitialization(*this, From->getType(),
5862 From->Classify(Context),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005863 Conversion, ConversionContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005864
John McCall1d318332010-01-12 00:44:57 +00005865 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005866 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005867 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005868 return;
5869 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005870
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005871 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005872 // derived to base as such conversions are given Conversion Rank. They only
5873 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5874 QualType FromCanon
5875 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5876 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5877 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5878 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005879 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005880 return;
5881 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005882
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005883 // To determine what the conversion from the result of calling the
5884 // conversion function to the type we're eventually trying to
5885 // convert to (ToType), we need to synthesize a call to the
5886 // conversion function and attempt copy initialization from it. This
5887 // makes sure that we get the right semantics with respect to
5888 // lvalues/rvalues and the type. Fortunately, we can allocate this
5889 // call on the stack and we don't need its arguments to be
5890 // well-formed.
John McCallf4b88a42012-03-10 09:33:50 +00005891 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005892 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00005893 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5894 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00005895 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00005896 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00005897
Richard Smith87c1f1f2011-07-13 22:53:21 +00005898 QualType ConversionType = Conversion->getConversionType();
5899 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor7d14d382010-11-13 19:36:57 +00005900 Candidate.Viable = false;
5901 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5902 return;
5903 }
5904
Richard Smith87c1f1f2011-07-13 22:53:21 +00005905 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCallf89e55a2010-11-18 06:31:45 +00005906
Mike Stump1eb44332009-09-09 15:08:12 +00005907 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00005908 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5909 // allocator).
Richard Smith87c1f1f2011-07-13 22:53:21 +00005910 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00005911 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00005912 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00005913 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00005914 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005915 /*SuppressUserConversions=*/true,
John McCallf85e1932011-06-15 23:02:42 +00005916 /*InOverloadResolution=*/false,
5917 /*AllowObjCWritebackConversion=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00005918
John McCall1d318332010-01-12 00:44:57 +00005919 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005920 case ImplicitConversionSequence::StandardConversion:
5921 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005922
Douglas Gregorc520c842010-04-12 23:42:09 +00005923 // C++ [over.ics.user]p3:
5924 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005925 // conversion function template, the second standard conversion sequence
Douglas Gregorc520c842010-04-12 23:42:09 +00005926 // shall have exact match rank.
5927 if (Conversion->getPrimaryTemplate() &&
5928 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5929 Candidate.Viable = false;
5930 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5931 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005932
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005933 // C++0x [dcl.init.ref]p5:
5934 // In the second case, if the reference is an rvalue reference and
5935 // the second standard conversion sequence of the user-defined
5936 // conversion sequence includes an lvalue-to-rvalue conversion, the
5937 // program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005938 if (ToType->isRValueReferenceType() &&
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005939 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5940 Candidate.Viable = false;
5941 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5942 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005943 break;
5944
5945 case ImplicitConversionSequence::BadConversion:
5946 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005947 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005948 break;
5949
5950 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00005951 llvm_unreachable(
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005952 "Can only end up with a standard conversion sequence or failure");
5953 }
5954}
5955
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005956/// \brief Adds a conversion function template specialization
5957/// candidate to the overload set, using template argument deduction
5958/// to deduce the template arguments of the conversion function
5959/// template from the type that we are converting to (C++
5960/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00005961void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005962Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005963 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005964 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005965 Expr *From, QualType ToType,
5966 OverloadCandidateSet &CandidateSet) {
5967 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5968 "Only conversion function templates permitted here");
5969
Douglas Gregor3f396022009-09-28 04:47:19 +00005970 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5971 return;
5972
Craig Topper93e45992012-09-19 02:26:47 +00005973 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005974 CXXConversionDecl *Specialization = 0;
5975 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00005976 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005977 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005978 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005979 Candidate.FoundDecl = FoundDecl;
5980 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5981 Candidate.Viable = false;
5982 Candidate.FailureKind = ovl_fail_bad_deduction;
5983 Candidate.IsSurrogate = false;
5984 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005985 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005986 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005987 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005988 return;
5989 }
Mike Stump1eb44332009-09-09 15:08:12 +00005990
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005991 // Add the conversion function template specialization produced by
5992 // template argument deduction as a candidate.
5993 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00005994 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00005995 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005996}
5997
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005998/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5999/// converts the given @c Object to a function pointer via the
6000/// conversion function @c Conversion, and then attempts to call it
6001/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6002/// the type of function that we'll eventually be calling.
6003void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00006004 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00006005 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00006006 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006007 Expr *Object,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006008 ArrayRef<Expr *> Args,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006009 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00006010 if (!CandidateSet.isNewCandidate(Conversion))
6011 return;
6012
Douglas Gregor7edfb692009-11-23 12:27:39 +00006013 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00006014 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00006015
Ahmed Charles13a140c2012-02-25 11:00:22 +00006016 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00006017 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006018 Candidate.Function = 0;
6019 Candidate.Surrogate = Conversion;
6020 Candidate.Viable = true;
6021 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00006022 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00006023 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006024
6025 // Determine the implicit conversion sequence for the implicit
6026 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00006027 ImplicitConversionSequence ObjectInit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006028 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006029 Object->Classify(Context),
6030 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00006031 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006032 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006033 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00006034 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006035 return;
6036 }
6037
6038 // The first conversion is actually a user-defined conversion whose
6039 // first conversion is ObjectInit's standard conversion (which is
6040 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00006041 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006042 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00006043 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00006044 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006045 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00006046 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00006047 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006048 = Candidate.Conversions[0].UserDefined.Before;
6049 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6050
Mike Stump1eb44332009-09-09 15:08:12 +00006051 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006052 unsigned NumArgsInProto = Proto->getNumArgs();
6053
6054 // (C++ 13.3.2p2): A candidate function having fewer than m
6055 // parameters is viable only if it has an ellipsis in its parameter
6056 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00006057 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006058 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006059 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006060 return;
6061 }
6062
6063 // Function types don't have any default arguments, so just check if
6064 // we have enough arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00006065 if (Args.size() < NumArgsInProto) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006066 // Not enough arguments.
6067 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006068 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006069 return;
6070 }
6071
6072 // Determine the implicit conversion sequences for each of the
6073 // arguments.
Richard Smith958ba642013-05-05 15:51:06 +00006074 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006075 if (ArgIdx < NumArgsInProto) {
6076 // (C++ 13.3.2p3): for F to be a viable function, there shall
6077 // exist for each argument an implicit conversion sequence
6078 // (13.3.3.1) that converts that argument to the corresponding
6079 // parameter of F.
6080 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00006081 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006082 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00006083 /*SuppressUserConversions=*/false,
John McCallf85e1932011-06-15 23:02:42 +00006084 /*InOverloadResolution=*/false,
6085 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00006086 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00006087 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006088 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006089 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006090 break;
6091 }
6092 } else {
6093 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6094 // argument for which there is no corresponding parameter is
6095 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00006096 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006097 }
6098 }
6099}
6100
Douglas Gregor063daf62009-03-13 18:40:31 +00006101/// \brief Add overload candidates for overloaded operators that are
6102/// member functions.
6103///
6104/// Add the overloaded operator candidates that are member functions
6105/// for the operator Op that was used in an operator expression such
6106/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6107/// CandidateSet will store the added overload candidates. (C++
6108/// [over.match.oper]).
6109void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6110 SourceLocation OpLoc,
Richard Smith958ba642013-05-05 15:51:06 +00006111 ArrayRef<Expr *> Args,
Douglas Gregor063daf62009-03-13 18:40:31 +00006112 OverloadCandidateSet& CandidateSet,
6113 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00006114 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6115
6116 // C++ [over.match.oper]p3:
6117 // For a unary operator @ with an operand of a type whose
6118 // cv-unqualified version is T1, and for a binary operator @ with
6119 // a left operand of a type whose cv-unqualified version is T1 and
6120 // a right operand of a type whose cv-unqualified version is T2,
6121 // three sets of candidate functions, designated member
6122 // candidates, non-member candidates and built-in candidates, are
6123 // constructed as follows:
6124 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00006125
Richard Smithe410be92013-04-20 12:41:22 +00006126 // -- If T1 is a complete class type or a class currently being
6127 // defined, the set of member candidates is the result of the
6128 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6129 // the set of member candidates is empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00006130 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smithe410be92013-04-20 12:41:22 +00006131 // Complete the type if it can be completed.
6132 RequireCompleteType(OpLoc, T1, 0);
6133 // If the type is neither complete nor being defined, bail out now.
6134 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor8a5ae242009-08-27 23:35:55 +00006135 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006136
John McCalla24dc2e2009-11-17 02:14:36 +00006137 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6138 LookupQualifiedName(Operators, T1Rec->getDecl());
6139 Operators.suppressDiagnostics();
6140
Mike Stump1eb44332009-09-09 15:08:12 +00006141 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00006142 OperEnd = Operators.end();
6143 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00006144 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00006145 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola548107e2013-04-29 19:29:25 +00006146 Args[0]->Classify(Context),
Richard Smith958ba642013-05-05 15:51:06 +00006147 Args.slice(1),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006148 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00006149 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00006150 }
Douglas Gregor96176b32008-11-18 23:14:02 +00006151}
6152
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006153/// AddBuiltinCandidate - Add a candidate for a built-in
6154/// operator. ResultTy and ParamTys are the result and parameter types
6155/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006156/// arguments being passed to the candidate. IsAssignmentOperator
6157/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006158/// operator. NumContextualBoolArguments is the number of arguments
6159/// (at the beginning of the argument list) that will be contextually
6160/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00006161void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smith958ba642013-05-05 15:51:06 +00006162 ArrayRef<Expr *> Args,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006163 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006164 bool IsAssignmentOperator,
6165 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00006166 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00006167 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00006168
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006169 // Add this candidate
Richard Smith958ba642013-05-05 15:51:06 +00006170 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCall9aa472c2010-03-19 07:35:19 +00006171 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006172 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00006173 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00006174 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006175 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smith958ba642013-05-05 15:51:06 +00006176 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006177 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6178
6179 // Determine the implicit conversion sequences for each of the
6180 // arguments.
6181 Candidate.Viable = true;
Richard Smith958ba642013-05-05 15:51:06 +00006182 Candidate.ExplicitCallArguments = Args.size();
6183 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006184 // C++ [over.match.oper]p4:
6185 // For the built-in assignment operators, conversions of the
6186 // left operand are restricted as follows:
6187 // -- no temporaries are introduced to hold the left operand, and
6188 // -- no user-defined conversions are applied to the left
6189 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00006190 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006191 //
6192 // We block these conversions by turning off user-defined
6193 // conversions, since that is the only way that initialization of
6194 // a reference to a non-class type can occur from something that
6195 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006196 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00006197 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006198 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00006199 Candidate.Conversions[ArgIdx]
6200 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006201 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00006202 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006203 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00006204 ArgIdx == 0 && IsAssignmentOperator,
John McCallf85e1932011-06-15 23:02:42 +00006205 /*InOverloadResolution=*/false,
6206 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00006207 getLangOpts().ObjCAutoRefCount);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006208 }
John McCall1d318332010-01-12 00:44:57 +00006209 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006210 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006211 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00006212 break;
6213 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006214 }
6215}
6216
Craig Topperfe09f3f2013-07-01 06:29:40 +00006217namespace {
6218
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006219/// BuiltinCandidateTypeSet - A set of types that will be used for the
6220/// candidate operator functions for built-in operators (C++
6221/// [over.built]). The types are separated into pointer types and
6222/// enumeration types.
6223class BuiltinCandidateTypeSet {
6224 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006225 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006226
6227 /// PointerTypes - The set of pointer types that will be used in the
6228 /// built-in candidates.
6229 TypeSet PointerTypes;
6230
Sebastian Redl78eb8742009-04-19 21:53:20 +00006231 /// MemberPointerTypes - The set of member pointer types that will be
6232 /// used in the built-in candidates.
6233 TypeSet MemberPointerTypes;
6234
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006235 /// EnumerationTypes - The set of enumeration types that will be
6236 /// used in the built-in candidates.
6237 TypeSet EnumerationTypes;
6238
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006239 /// \brief The set of vector types that will be used in the built-in
Douglas Gregor26bcf672010-05-19 03:21:00 +00006240 /// candidates.
6241 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00006242
6243 /// \brief A flag indicating non-record types are viable candidates
6244 bool HasNonRecordTypes;
6245
6246 /// \brief A flag indicating whether either arithmetic or enumeration types
6247 /// were present in the candidate set.
6248 bool HasArithmeticOrEnumeralTypes;
6249
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006250 /// \brief A flag indicating whether the nullptr type was present in the
6251 /// candidate set.
6252 bool HasNullPtrType;
6253
Douglas Gregor5842ba92009-08-24 15:23:48 +00006254 /// Sema - The semantic analysis instance where we are building the
6255 /// candidate type set.
6256 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00006257
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006258 /// Context - The AST context in which we will build the type sets.
6259 ASTContext &Context;
6260
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006261 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6262 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00006263 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006264
6265public:
6266 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006267 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006268
Mike Stump1eb44332009-09-09 15:08:12 +00006269 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00006270 : HasNonRecordTypes(false),
6271 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006272 HasNullPtrType(false),
Chandler Carruth6a577462010-12-13 01:44:01 +00006273 SemaRef(SemaRef),
6274 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006275
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006276 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006277 SourceLocation Loc,
6278 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006279 bool AllowExplicitConversions,
6280 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006281
6282 /// pointer_begin - First pointer type found;
6283 iterator pointer_begin() { return PointerTypes.begin(); }
6284
Sebastian Redl78eb8742009-04-19 21:53:20 +00006285 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006286 iterator pointer_end() { return PointerTypes.end(); }
6287
Sebastian Redl78eb8742009-04-19 21:53:20 +00006288 /// member_pointer_begin - First member pointer type found;
6289 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6290
6291 /// member_pointer_end - Past the last member pointer type found;
6292 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6293
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006294 /// enumeration_begin - First enumeration type found;
6295 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6296
Sebastian Redl78eb8742009-04-19 21:53:20 +00006297 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006298 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006299
Douglas Gregor26bcf672010-05-19 03:21:00 +00006300 iterator vector_begin() { return VectorTypes.begin(); }
6301 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00006302
6303 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6304 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006305 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006306};
6307
Craig Topperfe09f3f2013-07-01 06:29:40 +00006308} // end anonymous namespace
6309
Sebastian Redl78eb8742009-04-19 21:53:20 +00006310/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006311/// the set of pointer types along with any more-qualified variants of
6312/// that type. For example, if @p Ty is "int const *", this routine
6313/// will add "int const *", "int const volatile *", "int const
6314/// restrict *", and "int const volatile restrict *" to the set of
6315/// pointer types. Returns true if the add of @p Ty itself succeeded,
6316/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006317///
6318/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006319bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00006320BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6321 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00006322
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006323 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006324 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006325 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006326
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006327 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00006328 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006329 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006330 if (!PointerTy) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006331 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6332 PointeeTy = PTy->getPointeeType();
6333 buildObjCPtr = true;
6334 } else {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006335 PointeeTy = PointerTy->getPointeeType();
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006336 }
6337
Sebastian Redla9efada2009-11-18 20:39:26 +00006338 // Don't add qualified variants of arrays. For one, they're not allowed
6339 // (the qualifier would sink to the element type), and for another, the
6340 // only overload situation where it matters is subscript or pointer +- int,
6341 // and those shouldn't have qualifier variants anyway.
6342 if (PointeeTy->isArrayType())
6343 return true;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006344
John McCall0953e762009-09-24 19:53:00 +00006345 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006346 bool hasVolatile = VisibleQuals.hasVolatile();
6347 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006348
John McCall0953e762009-09-24 19:53:00 +00006349 // Iterate through all strict supersets of BaseCVR.
6350 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6351 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006352 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006353 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006354
6355 // Skip over restrict if no restrict found anywhere in the types, or if
6356 // the type cannot be restrict-qualified.
6357 if ((CVR & Qualifiers::Restrict) &&
6358 (!hasRestrict ||
6359 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6360 continue;
6361
6362 // Build qualified pointee type.
John McCall0953e762009-09-24 19:53:00 +00006363 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006364
6365 // Build qualified pointer type.
6366 QualType QPointerTy;
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006367 if (!buildObjCPtr)
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006368 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006369 else
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006370 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6371
6372 // Insert qualified pointer type.
6373 PointerTypes.insert(QPointerTy);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006374 }
6375
6376 return true;
6377}
6378
Sebastian Redl78eb8742009-04-19 21:53:20 +00006379/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6380/// to the set of pointer types along with any more-qualified variants of
6381/// that type. For example, if @p Ty is "int const *", this routine
6382/// will add "int const *", "int const volatile *", "int const
6383/// restrict *", and "int const volatile restrict *" to the set of
6384/// pointer types. Returns true if the add of @p Ty itself succeeded,
6385/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006386///
6387/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006388bool
6389BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6390 QualType Ty) {
6391 // Insert this type.
6392 if (!MemberPointerTypes.insert(Ty))
6393 return false;
6394
John McCall0953e762009-09-24 19:53:00 +00006395 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6396 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00006397
John McCall0953e762009-09-24 19:53:00 +00006398 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00006399 // Don't add qualified variants of arrays. For one, they're not allowed
6400 // (the qualifier would sink to the element type), and for another, the
6401 // only overload situation where it matters is subscript or pointer +- int,
6402 // and those shouldn't have qualifier variants anyway.
6403 if (PointeeTy->isArrayType())
6404 return true;
John McCall0953e762009-09-24 19:53:00 +00006405 const Type *ClassTy = PointerTy->getClass();
6406
6407 // Iterate through all strict supersets of the pointee type's CVR
6408 // qualifiers.
6409 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6410 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6411 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006412
John McCall0953e762009-09-24 19:53:00 +00006413 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006414 MemberPointerTypes.insert(
6415 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00006416 }
6417
6418 return true;
6419}
6420
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006421/// AddTypesConvertedFrom - Add each of the types to which the type @p
6422/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00006423/// primarily interested in pointer types and enumeration types. We also
6424/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006425/// AllowUserConversions is true if we should look at the conversion
6426/// functions of a class type, and AllowExplicitConversions if we
6427/// should also include the explicit conversion functions of a class
6428/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00006429void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006430BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006431 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006432 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006433 bool AllowExplicitConversions,
6434 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006435 // Only deal with canonical types.
6436 Ty = Context.getCanonicalType(Ty);
6437
6438 // Look through reference types; they aren't part of the type of an
6439 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00006440 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006441 Ty = RefTy->getPointeeType();
6442
John McCall3b657512011-01-19 10:06:00 +00006443 // If we're dealing with an array type, decay to the pointer.
6444 if (Ty->isArrayType())
6445 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6446
6447 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006448 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006449
Chandler Carruth6a577462010-12-13 01:44:01 +00006450 // Flag if we ever add a non-record type.
6451 const RecordType *TyRec = Ty->getAs<RecordType>();
6452 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6453
Chandler Carruth6a577462010-12-13 01:44:01 +00006454 // Flag if we encounter an arithmetic type.
6455 HasArithmeticOrEnumeralTypes =
6456 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6457
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006458 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6459 PointerTypes.insert(Ty);
6460 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006461 // Insert our type, and its more-qualified variants, into the set
6462 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006463 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006464 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00006465 } else if (Ty->isMemberPointerType()) {
6466 // Member pointers are far easier, since the pointee can't be converted.
6467 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6468 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006469 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006470 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00006471 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006472 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006473 // We treat vector types as arithmetic types in many contexts as an
6474 // extension.
6475 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00006476 VectorTypes.insert(Ty);
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006477 } else if (Ty->isNullPtrType()) {
6478 HasNullPtrType = true;
Chandler Carruth6a577462010-12-13 01:44:01 +00006479 } else if (AllowUserConversions && TyRec) {
6480 // No conversion functions in incomplete types.
6481 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6482 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006483
Chandler Carruth6a577462010-12-13 01:44:01 +00006484 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006485 std::pair<CXXRecordDecl::conversion_iterator,
6486 CXXRecordDecl::conversion_iterator>
6487 Conversions = ClassDecl->getVisibleConversionFunctions();
6488 for (CXXRecordDecl::conversion_iterator
6489 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006490 NamedDecl *D = I.getDecl();
6491 if (isa<UsingShadowDecl>(D))
6492 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006493
Chandler Carruth6a577462010-12-13 01:44:01 +00006494 // Skip conversion function templates; they don't tell us anything
6495 // about which builtin types we can convert to.
6496 if (isa<FunctionTemplateDecl>(D))
6497 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006498
Chandler Carruth6a577462010-12-13 01:44:01 +00006499 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6500 if (AllowExplicitConversions || !Conv->isExplicit()) {
6501 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6502 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006503 }
6504 }
6505 }
6506}
6507
Douglas Gregor19b7b152009-08-24 13:43:27 +00006508/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6509/// the volatile- and non-volatile-qualified assignment operators for the
6510/// given type to the candidate set.
6511static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6512 QualType T,
Richard Smith958ba642013-05-05 15:51:06 +00006513 ArrayRef<Expr *> Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006514 OverloadCandidateSet &CandidateSet) {
6515 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00006516
Douglas Gregor19b7b152009-08-24 13:43:27 +00006517 // T& operator=(T&, T)
6518 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6519 ParamTypes[1] = T;
Richard Smith958ba642013-05-05 15:51:06 +00006520 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006521 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00006522
Douglas Gregor19b7b152009-08-24 13:43:27 +00006523 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6524 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00006525 ParamTypes[0]
6526 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00006527 ParamTypes[1] = T;
Richard Smith958ba642013-05-05 15:51:06 +00006528 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00006529 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00006530 }
6531}
Mike Stump1eb44332009-09-09 15:08:12 +00006532
Sebastian Redl9994a342009-10-25 17:03:50 +00006533/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6534/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006535static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6536 Qualifiers VRQuals;
6537 const RecordType *TyRec;
6538 if (const MemberPointerType *RHSMPType =
6539 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00006540 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006541 else
6542 TyRec = ArgExpr->getType()->getAs<RecordType>();
6543 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006544 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006545 VRQuals.addVolatile();
6546 VRQuals.addRestrict();
6547 return VRQuals;
6548 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006549
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006550 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00006551 if (!ClassDecl->hasDefinition())
6552 return VRQuals;
6553
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006554 std::pair<CXXRecordDecl::conversion_iterator,
6555 CXXRecordDecl::conversion_iterator>
6556 Conversions = ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006557
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006558 for (CXXRecordDecl::conversion_iterator
6559 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00006560 NamedDecl *D = I.getDecl();
6561 if (isa<UsingShadowDecl>(D))
6562 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6563 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006564 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6565 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6566 CanTy = ResTypeRef->getPointeeType();
6567 // Need to go down the pointer/mempointer chain and add qualifiers
6568 // as see them.
6569 bool done = false;
6570 while (!done) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006571 if (CanTy.isRestrictQualified())
6572 VRQuals.addRestrict();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006573 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6574 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006575 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006576 CanTy->getAs<MemberPointerType>())
6577 CanTy = ResTypeMPtr->getPointeeType();
6578 else
6579 done = true;
6580 if (CanTy.isVolatileQualified())
6581 VRQuals.addVolatile();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006582 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6583 return VRQuals;
6584 }
6585 }
6586 }
6587 return VRQuals;
6588}
John McCall00071ec2010-11-13 05:51:15 +00006589
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006590namespace {
John McCall00071ec2010-11-13 05:51:15 +00006591
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006592/// \brief Helper class to manage the addition of builtin operator overload
6593/// candidates. It provides shared state and utility methods used throughout
6594/// the process, as well as a helper method to add each group of builtin
6595/// operator overloads from the standard to a candidate set.
6596class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00006597 // Common instance state available to all overload candidate addition methods.
6598 Sema &S;
Richard Smith958ba642013-05-05 15:51:06 +00006599 ArrayRef<Expr *> Args;
Chandler Carruth6d695582010-12-12 10:35:00 +00006600 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00006601 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006602 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruth6d695582010-12-12 10:35:00 +00006603 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006604
Chandler Carruth6d695582010-12-12 10:35:00 +00006605 // Define some constants used to index and iterate over the arithemetic types
6606 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00006607 // The "promoted arithmetic types" are the arithmetic
6608 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00006609 static const unsigned FirstIntegralType = 3;
Richard Smith3c2fcf82012-06-10 08:00:26 +00006610 static const unsigned LastIntegralType = 20;
John McCall00071ec2010-11-13 05:51:15 +00006611 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006612 LastPromotedIntegralType = 11;
John McCall00071ec2010-11-13 05:51:15 +00006613 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006614 LastPromotedArithmeticType = 11;
6615 static const unsigned NumArithmeticTypes = 20;
John McCall00071ec2010-11-13 05:51:15 +00006616
Chandler Carruth6d695582010-12-12 10:35:00 +00006617 /// \brief Get the canonical type for a given arithmetic type index.
6618 CanQualType getArithmeticType(unsigned index) {
6619 assert(index < NumArithmeticTypes);
6620 static CanQualType ASTContext::* const
6621 ArithmeticTypes[NumArithmeticTypes] = {
6622 // Start of promoted types.
6623 &ASTContext::FloatTy,
6624 &ASTContext::DoubleTy,
6625 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00006626
Chandler Carruth6d695582010-12-12 10:35:00 +00006627 // Start of integral types.
6628 &ASTContext::IntTy,
6629 &ASTContext::LongTy,
6630 &ASTContext::LongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006631 &ASTContext::Int128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006632 &ASTContext::UnsignedIntTy,
6633 &ASTContext::UnsignedLongTy,
6634 &ASTContext::UnsignedLongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006635 &ASTContext::UnsignedInt128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006636 // End of promoted types.
6637
6638 &ASTContext::BoolTy,
6639 &ASTContext::CharTy,
6640 &ASTContext::WCharTy,
6641 &ASTContext::Char16Ty,
6642 &ASTContext::Char32Ty,
6643 &ASTContext::SignedCharTy,
6644 &ASTContext::ShortTy,
6645 &ASTContext::UnsignedCharTy,
6646 &ASTContext::UnsignedShortTy,
6647 // End of integral types.
Richard Smith3c2fcf82012-06-10 08:00:26 +00006648 // FIXME: What about complex? What about half?
Chandler Carruth6d695582010-12-12 10:35:00 +00006649 };
6650 return S.Context.*ArithmeticTypes[index];
6651 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006652
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006653 /// \brief Gets the canonical type resulting from the usual arithemetic
6654 /// converions for the given arithmetic types.
6655 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6656 // Accelerator table for performing the usual arithmetic conversions.
6657 // The rules are basically:
6658 // - if either is floating-point, use the wider floating-point
6659 // - if same signedness, use the higher rank
6660 // - if same size, use unsigned of the higher rank
6661 // - use the larger type
6662 // These rules, together with the axiom that higher ranks are
6663 // never smaller, are sufficient to precompute all of these results
6664 // *except* when dealing with signed types of higher rank.
6665 // (we could precompute SLL x UI for all known platforms, but it's
6666 // better not to make any assumptions).
Richard Smith3c2fcf82012-06-10 08:00:26 +00006667 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006668 enum PromotedType {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006669 Dep=-1,
6670 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006671 };
Nuno Lopes79e244f2012-04-21 14:45:25 +00006672 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006673 [LastPromotedArithmeticType] = {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006674/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6675/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6676/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6677/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6678/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6679/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6680/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6681/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6682/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6683/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6684/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006685 };
6686
6687 assert(L < LastPromotedArithmeticType);
6688 assert(R < LastPromotedArithmeticType);
6689 int Idx = ConversionsTable[L][R];
6690
6691 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00006692 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006693
6694 // Slow path: we need to compare widths.
6695 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00006696 CanQualType LT = getArithmeticType(L),
6697 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006698 unsigned LW = S.Context.getIntWidth(LT),
6699 RW = S.Context.getIntWidth(RT);
6700
6701 // If they're different widths, use the signed type.
6702 if (LW > RW) return LT;
6703 else if (LW < RW) return RT;
6704
6705 // Otherwise, use the unsigned type of the signed type's rank.
6706 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6707 assert(L == SLL || R == SLL);
6708 return S.Context.UnsignedLongLongTy;
6709 }
6710
Chandler Carruth3c69dc42010-12-12 09:22:45 +00006711 /// \brief Helper method to factor out the common pattern of adding overloads
6712 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006713 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006714 bool HasVolatile,
6715 bool HasRestrict) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006716 QualType ParamTypes[2] = {
6717 S.Context.getLValueReferenceType(CandidateTy),
6718 S.Context.IntTy
6719 };
6720
6721 // Non-volatile version.
Richard Smith958ba642013-05-05 15:51:06 +00006722 if (Args.size() == 1)
6723 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006724 else
Richard Smith958ba642013-05-05 15:51:06 +00006725 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006726
6727 // Use a heuristic to reduce number of builtin candidates in the set:
6728 // add volatile version only if there are conversions to a volatile type.
6729 if (HasVolatile) {
6730 ParamTypes[0] =
6731 S.Context.getLValueReferenceType(
6732 S.Context.getVolatileType(CandidateTy));
Richard Smith958ba642013-05-05 15:51:06 +00006733 if (Args.size() == 1)
6734 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006735 else
Richard Smith958ba642013-05-05 15:51:06 +00006736 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006737 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006738
6739 // Add restrict version only if there are conversions to a restrict type
6740 // and our candidate type is a non-restrict-qualified pointer.
6741 if (HasRestrict && CandidateTy->isAnyPointerType() &&
6742 !CandidateTy.isRestrictQualified()) {
6743 ParamTypes[0]
6744 = S.Context.getLValueReferenceType(
6745 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smith958ba642013-05-05 15:51:06 +00006746 if (Args.size() == 1)
6747 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006748 else
Richard Smith958ba642013-05-05 15:51:06 +00006749 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006750
6751 if (HasVolatile) {
6752 ParamTypes[0]
6753 = S.Context.getLValueReferenceType(
6754 S.Context.getCVRQualifiedType(CandidateTy,
6755 (Qualifiers::Volatile |
6756 Qualifiers::Restrict)));
Richard Smith958ba642013-05-05 15:51:06 +00006757 if (Args.size() == 1)
6758 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006759 else
Richard Smith958ba642013-05-05 15:51:06 +00006760 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006761 }
6762 }
6763
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006764 }
6765
6766public:
6767 BuiltinOperatorOverloadBuilder(
Richard Smith958ba642013-05-05 15:51:06 +00006768 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006769 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00006770 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006771 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006772 OverloadCandidateSet &CandidateSet)
Richard Smith958ba642013-05-05 15:51:06 +00006773 : S(S), Args(Args),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006774 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00006775 HasArithmeticOrEnumeralCandidateType(
6776 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006777 CandidateTypes(CandidateTypes),
6778 CandidateSet(CandidateSet) {
6779 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00006780 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006781 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006782 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006783 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006784 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006785 assert(getArithmeticType(FirstPromotedArithmeticType)
6786 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006787 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006788 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006789 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006790 "Invalid last promoted arithmetic type");
6791 }
6792
6793 // C++ [over.built]p3:
6794 //
6795 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6796 // is either volatile or empty, there exist candidate operator
6797 // functions of the form
6798 //
6799 // VQ T& operator++(VQ T&);
6800 // T operator++(VQ T&, int);
6801 //
6802 // C++ [over.built]p4:
6803 //
6804 // For every pair (T, VQ), where T is an arithmetic type other
6805 // than bool, and VQ is either volatile or empty, there exist
6806 // candidate operator functions of the form
6807 //
6808 // VQ T& operator--(VQ T&);
6809 // T operator--(VQ T&, int);
6810 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006811 if (!HasArithmeticOrEnumeralCandidateType)
6812 return;
6813
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006814 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6815 Arith < NumArithmeticTypes; ++Arith) {
6816 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00006817 getArithmeticType(Arith),
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006818 VisibleTypeConversionsQuals.hasVolatile(),
6819 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006820 }
6821 }
6822
6823 // C++ [over.built]p5:
6824 //
6825 // For every pair (T, VQ), where T is a cv-qualified or
6826 // cv-unqualified object type, and VQ is either volatile or
6827 // empty, there exist candidate operator functions of the form
6828 //
6829 // T*VQ& operator++(T*VQ&);
6830 // T*VQ& operator--(T*VQ&);
6831 // T* operator++(T*VQ&, int);
6832 // T* operator--(T*VQ&, int);
6833 void addPlusPlusMinusMinusPointerOverloads() {
6834 for (BuiltinCandidateTypeSet::iterator
6835 Ptr = CandidateTypes[0].pointer_begin(),
6836 PtrEnd = CandidateTypes[0].pointer_end();
6837 Ptr != PtrEnd; ++Ptr) {
6838 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006839 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006840 continue;
6841
6842 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006843 (!(*Ptr).isVolatileQualified() &&
6844 VisibleTypeConversionsQuals.hasVolatile()),
6845 (!(*Ptr).isRestrictQualified() &&
6846 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006847 }
6848 }
6849
6850 // C++ [over.built]p6:
6851 // For every cv-qualified or cv-unqualified object type T, there
6852 // exist candidate operator functions of the form
6853 //
6854 // T& operator*(T*);
6855 //
6856 // C++ [over.built]p7:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006857 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006858 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006859 // T& operator*(T*);
6860 void addUnaryStarPointerOverloads() {
6861 for (BuiltinCandidateTypeSet::iterator
6862 Ptr = CandidateTypes[0].pointer_begin(),
6863 PtrEnd = CandidateTypes[0].pointer_end();
6864 Ptr != PtrEnd; ++Ptr) {
6865 QualType ParamTy = *Ptr;
6866 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006867 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6868 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006869
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006870 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6871 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6872 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006873
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006874 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smith958ba642013-05-05 15:51:06 +00006875 &ParamTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006876 }
6877 }
6878
6879 // C++ [over.built]p9:
6880 // For every promoted arithmetic type T, there exist candidate
6881 // operator functions of the form
6882 //
6883 // T operator+(T);
6884 // T operator-(T);
6885 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006886 if (!HasArithmeticOrEnumeralCandidateType)
6887 return;
6888
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006889 for (unsigned Arith = FirstPromotedArithmeticType;
6890 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006891 QualType ArithTy = getArithmeticType(Arith);
Richard Smith958ba642013-05-05 15:51:06 +00006892 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006893 }
6894
6895 // Extension: We also add these operators for vector types.
6896 for (BuiltinCandidateTypeSet::iterator
6897 Vec = CandidateTypes[0].vector_begin(),
6898 VecEnd = CandidateTypes[0].vector_end();
6899 Vec != VecEnd; ++Vec) {
6900 QualType VecTy = *Vec;
Richard Smith958ba642013-05-05 15:51:06 +00006901 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006902 }
6903 }
6904
6905 // C++ [over.built]p8:
6906 // For every type T, there exist candidate operator functions of
6907 // the form
6908 //
6909 // T* operator+(T*);
6910 void addUnaryPlusPointerOverloads() {
6911 for (BuiltinCandidateTypeSet::iterator
6912 Ptr = CandidateTypes[0].pointer_begin(),
6913 PtrEnd = CandidateTypes[0].pointer_end();
6914 Ptr != PtrEnd; ++Ptr) {
6915 QualType ParamTy = *Ptr;
Richard Smith958ba642013-05-05 15:51:06 +00006916 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006917 }
6918 }
6919
6920 // C++ [over.built]p10:
6921 // For every promoted integral type T, there exist candidate
6922 // operator functions of the form
6923 //
6924 // T operator~(T);
6925 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006926 if (!HasArithmeticOrEnumeralCandidateType)
6927 return;
6928
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006929 for (unsigned Int = FirstPromotedIntegralType;
6930 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006931 QualType IntTy = getArithmeticType(Int);
Richard Smith958ba642013-05-05 15:51:06 +00006932 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006933 }
6934
6935 // Extension: We also add this operator for vector types.
6936 for (BuiltinCandidateTypeSet::iterator
6937 Vec = CandidateTypes[0].vector_begin(),
6938 VecEnd = CandidateTypes[0].vector_end();
6939 Vec != VecEnd; ++Vec) {
6940 QualType VecTy = *Vec;
Richard Smith958ba642013-05-05 15:51:06 +00006941 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006942 }
6943 }
6944
6945 // C++ [over.match.oper]p16:
6946 // For every pointer to member type T, there exist candidate operator
6947 // functions of the form
6948 //
6949 // bool operator==(T,T);
6950 // bool operator!=(T,T);
6951 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6952 /// Set of (canonical) types that we've already handled.
6953 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6954
Richard Smith958ba642013-05-05 15:51:06 +00006955 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006956 for (BuiltinCandidateTypeSet::iterator
6957 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6958 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6959 MemPtr != MemPtrEnd;
6960 ++MemPtr) {
6961 // Don't add the same builtin candidate twice.
6962 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6963 continue;
6964
6965 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smith958ba642013-05-05 15:51:06 +00006966 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006967 }
6968 }
6969 }
6970
6971 // C++ [over.built]p15:
6972 //
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006973 // For every T, where T is an enumeration type, a pointer type, or
6974 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006975 //
6976 // bool operator<(T, T);
6977 // bool operator>(T, T);
6978 // bool operator<=(T, T);
6979 // bool operator>=(T, T);
6980 // bool operator==(T, T);
6981 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006982 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman97c67392012-09-18 21:52:24 +00006983 // C++ [over.match.oper]p3:
6984 // [...]the built-in candidates include all of the candidate operator
6985 // functions defined in 13.6 that, compared to the given operator, [...]
6986 // do not have the same parameter-type-list as any non-template non-member
6987 // candidate.
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006988 //
Eli Friedman97c67392012-09-18 21:52:24 +00006989 // Note that in practice, this only affects enumeration types because there
6990 // aren't any built-in candidates of record type, and a user-defined operator
6991 // must have an operand of record or enumeration type. Also, the only other
6992 // overloaded operator with enumeration arguments, operator=,
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006993 // cannot be overloaded for enumeration types, so this is the only place
6994 // where we must suppress candidates like this.
6995 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6996 UserDefinedBinaryOperators;
6997
Richard Smith958ba642013-05-05 15:51:06 +00006998 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006999 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7000 CandidateTypes[ArgIdx].enumeration_end()) {
7001 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7002 CEnd = CandidateSet.end();
7003 C != CEnd; ++C) {
7004 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7005 continue;
7006
Eli Friedman97c67392012-09-18 21:52:24 +00007007 if (C->Function->isFunctionTemplateSpecialization())
7008 continue;
7009
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007010 QualType FirstParamType =
7011 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7012 QualType SecondParamType =
7013 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7014
7015 // Skip if either parameter isn't of enumeral type.
7016 if (!FirstParamType->isEnumeralType() ||
7017 !SecondParamType->isEnumeralType())
7018 continue;
7019
7020 // Add this operator to the set of known user-defined operators.
7021 UserDefinedBinaryOperators.insert(
7022 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7023 S.Context.getCanonicalType(SecondParamType)));
7024 }
7025 }
7026 }
7027
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007028 /// Set of (canonical) types that we've already handled.
7029 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7030
Richard Smith958ba642013-05-05 15:51:06 +00007031 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007032 for (BuiltinCandidateTypeSet::iterator
7033 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7034 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7035 Ptr != PtrEnd; ++Ptr) {
7036 // Don't add the same builtin candidate twice.
7037 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7038 continue;
7039
7040 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smith958ba642013-05-05 15:51:06 +00007041 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007042 }
7043 for (BuiltinCandidateTypeSet::iterator
7044 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7045 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7046 Enum != EnumEnd; ++Enum) {
7047 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7048
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007049 // Don't add the same builtin candidate twice, or if a user defined
7050 // candidate exists.
7051 if (!AddedTypes.insert(CanonType) ||
7052 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7053 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007054 continue;
7055
7056 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smith958ba642013-05-05 15:51:06 +00007057 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007058 }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00007059
7060 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7061 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7062 if (AddedTypes.insert(NullPtrTy) &&
Richard Smith958ba642013-05-05 15:51:06 +00007063 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00007064 NullPtrTy))) {
7065 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smith958ba642013-05-05 15:51:06 +00007066 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00007067 CandidateSet);
7068 }
7069 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007070 }
7071 }
7072
7073 // C++ [over.built]p13:
7074 //
7075 // For every cv-qualified or cv-unqualified object type T
7076 // there exist candidate operator functions of the form
7077 //
7078 // T* operator+(T*, ptrdiff_t);
7079 // T& operator[](T*, ptrdiff_t); [BELOW]
7080 // T* operator-(T*, ptrdiff_t);
7081 // T* operator+(ptrdiff_t, T*);
7082 // T& operator[](ptrdiff_t, T*); [BELOW]
7083 //
7084 // C++ [over.built]p14:
7085 //
7086 // For every T, where T is a pointer to object type, there
7087 // exist candidate operator functions of the form
7088 //
7089 // ptrdiff_t operator-(T, T);
7090 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7091 /// Set of (canonical) types that we've already handled.
7092 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7093
7094 for (int Arg = 0; Arg < 2; ++Arg) {
7095 QualType AsymetricParamTypes[2] = {
7096 S.Context.getPointerDiffType(),
7097 S.Context.getPointerDiffType(),
7098 };
7099 for (BuiltinCandidateTypeSet::iterator
7100 Ptr = CandidateTypes[Arg].pointer_begin(),
7101 PtrEnd = CandidateTypes[Arg].pointer_end();
7102 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007103 QualType PointeeTy = (*Ptr)->getPointeeType();
7104 if (!PointeeTy->isObjectType())
7105 continue;
7106
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007107 AsymetricParamTypes[Arg] = *Ptr;
7108 if (Arg == 0 || Op == OO_Plus) {
7109 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7110 // T* operator+(ptrdiff_t, T*);
Richard Smith958ba642013-05-05 15:51:06 +00007111 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007112 }
7113 if (Op == OO_Minus) {
7114 // ptrdiff_t operator-(T, T);
7115 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7116 continue;
7117
7118 QualType ParamTypes[2] = { *Ptr, *Ptr };
7119 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smith958ba642013-05-05 15:51:06 +00007120 Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007121 }
7122 }
7123 }
7124 }
7125
7126 // C++ [over.built]p12:
7127 //
7128 // For every pair of promoted arithmetic types L and R, there
7129 // exist candidate operator functions of the form
7130 //
7131 // LR operator*(L, R);
7132 // LR operator/(L, R);
7133 // LR operator+(L, R);
7134 // LR operator-(L, R);
7135 // bool operator<(L, R);
7136 // bool operator>(L, R);
7137 // bool operator<=(L, R);
7138 // bool operator>=(L, R);
7139 // bool operator==(L, R);
7140 // bool operator!=(L, R);
7141 //
7142 // where LR is the result of the usual arithmetic conversions
7143 // between types L and R.
7144 //
7145 // C++ [over.built]p24:
7146 //
7147 // For every pair of promoted arithmetic types L and R, there exist
7148 // candidate operator functions of the form
7149 //
7150 // LR operator?(bool, L, R);
7151 //
7152 // where LR is the result of the usual arithmetic conversions
7153 // between types L and R.
7154 // Our candidates ignore the first parameter.
7155 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007156 if (!HasArithmeticOrEnumeralCandidateType)
7157 return;
7158
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007159 for (unsigned Left = FirstPromotedArithmeticType;
7160 Left < LastPromotedArithmeticType; ++Left) {
7161 for (unsigned Right = FirstPromotedArithmeticType;
7162 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007163 QualType LandR[2] = { getArithmeticType(Left),
7164 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007165 QualType Result =
7166 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007167 : getUsualArithmeticConversions(Left, Right);
Richard Smith958ba642013-05-05 15:51:06 +00007168 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007169 }
7170 }
7171
7172 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7173 // conditional operator for vector types.
7174 for (BuiltinCandidateTypeSet::iterator
7175 Vec1 = CandidateTypes[0].vector_begin(),
7176 Vec1End = CandidateTypes[0].vector_end();
7177 Vec1 != Vec1End; ++Vec1) {
7178 for (BuiltinCandidateTypeSet::iterator
7179 Vec2 = CandidateTypes[1].vector_begin(),
7180 Vec2End = CandidateTypes[1].vector_end();
7181 Vec2 != Vec2End; ++Vec2) {
7182 QualType LandR[2] = { *Vec1, *Vec2 };
7183 QualType Result = S.Context.BoolTy;
7184 if (!isComparison) {
7185 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7186 Result = *Vec1;
7187 else
7188 Result = *Vec2;
7189 }
7190
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
7196 // C++ [over.built]p17:
7197 //
7198 // For every pair of promoted integral types L and R, there
7199 // exist candidate operator functions of the form
7200 //
7201 // LR operator%(L, R);
7202 // LR operator&(L, R);
7203 // LR operator^(L, R);
7204 // LR operator|(L, R);
7205 // L operator<<(L, R);
7206 // L operator>>(L, R);
7207 //
7208 // where LR is the result of the usual arithmetic conversions
7209 // between types L and R.
7210 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007211 if (!HasArithmeticOrEnumeralCandidateType)
7212 return;
7213
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007214 for (unsigned Left = FirstPromotedIntegralType;
7215 Left < LastPromotedIntegralType; ++Left) {
7216 for (unsigned Right = FirstPromotedIntegralType;
7217 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007218 QualType LandR[2] = { getArithmeticType(Left),
7219 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007220 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7221 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007222 : getUsualArithmeticConversions(Left, Right);
Richard Smith958ba642013-05-05 15:51:06 +00007223 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007224 }
7225 }
7226 }
7227
7228 // C++ [over.built]p20:
7229 //
7230 // For every pair (T, VQ), where T is an enumeration or
7231 // pointer to member type and VQ is either volatile or
7232 // empty, there exist candidate operator functions of the form
7233 //
7234 // VQ T& operator=(VQ T&, T);
7235 void addAssignmentMemberPointerOrEnumeralOverloads() {
7236 /// Set of (canonical) types that we've already handled.
7237 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7238
7239 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7240 for (BuiltinCandidateTypeSet::iterator
7241 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7242 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7243 Enum != EnumEnd; ++Enum) {
7244 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7245 continue;
7246
Richard Smith958ba642013-05-05 15:51:06 +00007247 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007248 }
7249
7250 for (BuiltinCandidateTypeSet::iterator
7251 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7252 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7253 MemPtr != MemPtrEnd; ++MemPtr) {
7254 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7255 continue;
7256
Richard Smith958ba642013-05-05 15:51:06 +00007257 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007258 }
7259 }
7260 }
7261
7262 // C++ [over.built]p19:
7263 //
7264 // For every pair (T, VQ), where T is any type and VQ is either
7265 // volatile or empty, there exist candidate operator functions
7266 // of the form
7267 //
7268 // T*VQ& operator=(T*VQ&, T*);
7269 //
7270 // C++ [over.built]p21:
7271 //
7272 // For every pair (T, VQ), where T is a cv-qualified or
7273 // cv-unqualified object type and VQ is either volatile or
7274 // empty, there exist candidate operator functions of the form
7275 //
7276 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7277 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7278 void addAssignmentPointerOverloads(bool isEqualOp) {
7279 /// Set of (canonical) types that we've already handled.
7280 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7281
7282 for (BuiltinCandidateTypeSet::iterator
7283 Ptr = CandidateTypes[0].pointer_begin(),
7284 PtrEnd = CandidateTypes[0].pointer_end();
7285 Ptr != PtrEnd; ++Ptr) {
7286 // If this is operator=, keep track of the builtin candidates we added.
7287 if (isEqualOp)
7288 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007289 else if (!(*Ptr)->getPointeeType()->isObjectType())
7290 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007291
7292 // non-volatile version
7293 QualType ParamTypes[2] = {
7294 S.Context.getLValueReferenceType(*Ptr),
7295 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7296 };
Richard Smith958ba642013-05-05 15:51:06 +00007297 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007298 /*IsAssigmentOperator=*/ isEqualOp);
7299
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007300 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7301 VisibleTypeConversionsQuals.hasVolatile();
7302 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007303 // volatile version
7304 ParamTypes[0] =
7305 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007306 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007307 /*IsAssigmentOperator=*/isEqualOp);
7308 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007309
7310 if (!(*Ptr).isRestrictQualified() &&
7311 VisibleTypeConversionsQuals.hasRestrict()) {
7312 // restrict version
7313 ParamTypes[0]
7314 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007315 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007316 /*IsAssigmentOperator=*/isEqualOp);
7317
7318 if (NeedVolatile) {
7319 // volatile restrict version
7320 ParamTypes[0]
7321 = S.Context.getLValueReferenceType(
7322 S.Context.getCVRQualifiedType(*Ptr,
7323 (Qualifiers::Volatile |
7324 Qualifiers::Restrict)));
Richard Smith958ba642013-05-05 15:51:06 +00007325 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007326 /*IsAssigmentOperator=*/isEqualOp);
7327 }
7328 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007329 }
7330
7331 if (isEqualOp) {
7332 for (BuiltinCandidateTypeSet::iterator
7333 Ptr = CandidateTypes[1].pointer_begin(),
7334 PtrEnd = CandidateTypes[1].pointer_end();
7335 Ptr != PtrEnd; ++Ptr) {
7336 // Make sure we don't add the same candidate twice.
7337 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7338 continue;
7339
Chandler Carruth6df868e2010-12-12 08:17:55 +00007340 QualType ParamTypes[2] = {
7341 S.Context.getLValueReferenceType(*Ptr),
7342 *Ptr,
7343 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007344
7345 // non-volatile version
Richard Smith958ba642013-05-05 15:51:06 +00007346 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007347 /*IsAssigmentOperator=*/true);
7348
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007349 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7350 VisibleTypeConversionsQuals.hasVolatile();
7351 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007352 // volatile version
7353 ParamTypes[0] =
7354 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007355 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7356 /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007357 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007358
7359 if (!(*Ptr).isRestrictQualified() &&
7360 VisibleTypeConversionsQuals.hasRestrict()) {
7361 // restrict version
7362 ParamTypes[0]
7363 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007364 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7365 /*IsAssigmentOperator=*/true);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007366
7367 if (NeedVolatile) {
7368 // volatile restrict version
7369 ParamTypes[0]
7370 = S.Context.getLValueReferenceType(
7371 S.Context.getCVRQualifiedType(*Ptr,
7372 (Qualifiers::Volatile |
7373 Qualifiers::Restrict)));
Richard Smith958ba642013-05-05 15:51:06 +00007374 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7375 /*IsAssigmentOperator=*/true);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007376 }
7377 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007378 }
7379 }
7380 }
7381
7382 // C++ [over.built]p18:
7383 //
7384 // For every triple (L, VQ, R), where L is an arithmetic type,
7385 // VQ is either volatile or empty, and R is a promoted
7386 // arithmetic type, there exist candidate operator functions of
7387 // the form
7388 //
7389 // VQ L& operator=(VQ L&, R);
7390 // VQ L& operator*=(VQ L&, R);
7391 // VQ L& operator/=(VQ L&, R);
7392 // VQ L& operator+=(VQ L&, R);
7393 // VQ L& operator-=(VQ L&, R);
7394 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007395 if (!HasArithmeticOrEnumeralCandidateType)
7396 return;
7397
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007398 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7399 for (unsigned Right = FirstPromotedArithmeticType;
7400 Right < LastPromotedArithmeticType; ++Right) {
7401 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007402 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007403
7404 // Add this built-in operator as a candidate (VQ is empty).
7405 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007406 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smith958ba642013-05-05 15:51:06 +00007407 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007408 /*IsAssigmentOperator=*/isEqualOp);
7409
7410 // Add this built-in operator as a candidate (VQ is 'volatile').
7411 if (VisibleTypeConversionsQuals.hasVolatile()) {
7412 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007413 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007414 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smith958ba642013-05-05 15:51:06 +00007415 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007416 /*IsAssigmentOperator=*/isEqualOp);
7417 }
7418 }
7419 }
7420
7421 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7422 for (BuiltinCandidateTypeSet::iterator
7423 Vec1 = CandidateTypes[0].vector_begin(),
7424 Vec1End = CandidateTypes[0].vector_end();
7425 Vec1 != Vec1End; ++Vec1) {
7426 for (BuiltinCandidateTypeSet::iterator
7427 Vec2 = CandidateTypes[1].vector_begin(),
7428 Vec2End = CandidateTypes[1].vector_end();
7429 Vec2 != Vec2End; ++Vec2) {
7430 QualType ParamTypes[2];
7431 ParamTypes[1] = *Vec2;
7432 // Add this built-in operator as a candidate (VQ is empty).
7433 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smith958ba642013-05-05 15:51:06 +00007434 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007435 /*IsAssigmentOperator=*/isEqualOp);
7436
7437 // Add this built-in operator as a candidate (VQ is 'volatile').
7438 if (VisibleTypeConversionsQuals.hasVolatile()) {
7439 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7440 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smith958ba642013-05-05 15:51:06 +00007441 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007442 /*IsAssigmentOperator=*/isEqualOp);
7443 }
7444 }
7445 }
7446 }
7447
7448 // C++ [over.built]p22:
7449 //
7450 // For every triple (L, VQ, R), where L is an integral type, VQ
7451 // is either volatile or empty, and R is a promoted integral
7452 // type, there exist candidate operator functions of the form
7453 //
7454 // VQ L& operator%=(VQ L&, R);
7455 // VQ L& operator<<=(VQ L&, R);
7456 // VQ L& operator>>=(VQ L&, R);
7457 // VQ L& operator&=(VQ L&, R);
7458 // VQ L& operator^=(VQ L&, R);
7459 // VQ L& operator|=(VQ L&, R);
7460 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00007461 if (!HasArithmeticOrEnumeralCandidateType)
7462 return;
7463
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007464 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7465 for (unsigned Right = FirstPromotedIntegralType;
7466 Right < LastPromotedIntegralType; ++Right) {
7467 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007468 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007469
7470 // Add this built-in operator as a candidate (VQ is empty).
7471 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007472 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smith958ba642013-05-05 15:51:06 +00007473 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007474 if (VisibleTypeConversionsQuals.hasVolatile()) {
7475 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00007476 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007477 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7478 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smith958ba642013-05-05 15:51:06 +00007479 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007480 }
7481 }
7482 }
7483 }
7484
7485 // C++ [over.operator]p23:
7486 //
7487 // There also exist candidate operator functions of the form
7488 //
7489 // bool operator!(bool);
7490 // bool operator&&(bool, bool);
7491 // bool operator||(bool, bool);
7492 void addExclaimOverload() {
7493 QualType ParamTy = S.Context.BoolTy;
Richard Smith958ba642013-05-05 15:51:06 +00007494 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007495 /*IsAssignmentOperator=*/false,
7496 /*NumContextualBoolArguments=*/1);
7497 }
7498 void addAmpAmpOrPipePipeOverload() {
7499 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smith958ba642013-05-05 15:51:06 +00007500 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007501 /*IsAssignmentOperator=*/false,
7502 /*NumContextualBoolArguments=*/2);
7503 }
7504
7505 // C++ [over.built]p13:
7506 //
7507 // For every cv-qualified or cv-unqualified object type T there
7508 // exist candidate operator functions of the form
7509 //
7510 // T* operator+(T*, ptrdiff_t); [ABOVE]
7511 // T& operator[](T*, ptrdiff_t);
7512 // T* operator-(T*, ptrdiff_t); [ABOVE]
7513 // T* operator+(ptrdiff_t, T*); [ABOVE]
7514 // T& operator[](ptrdiff_t, T*);
7515 void addSubscriptOverloads() {
7516 for (BuiltinCandidateTypeSet::iterator
7517 Ptr = CandidateTypes[0].pointer_begin(),
7518 PtrEnd = CandidateTypes[0].pointer_end();
7519 Ptr != PtrEnd; ++Ptr) {
7520 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7521 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007522 if (!PointeeType->isObjectType())
7523 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007524
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007525 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7526
7527 // T& operator[](T*, ptrdiff_t)
Richard Smith958ba642013-05-05 15:51:06 +00007528 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007529 }
7530
7531 for (BuiltinCandidateTypeSet::iterator
7532 Ptr = CandidateTypes[1].pointer_begin(),
7533 PtrEnd = CandidateTypes[1].pointer_end();
7534 Ptr != PtrEnd; ++Ptr) {
7535 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7536 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007537 if (!PointeeType->isObjectType())
7538 continue;
7539
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007540 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7541
7542 // T& operator[](ptrdiff_t, T*)
Richard Smith958ba642013-05-05 15:51:06 +00007543 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007544 }
7545 }
7546
7547 // C++ [over.built]p11:
7548 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7549 // C1 is the same type as C2 or is a derived class of C2, T is an object
7550 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7551 // there exist candidate operator functions of the form
7552 //
7553 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7554 //
7555 // where CV12 is the union of CV1 and CV2.
7556 void addArrowStarOverloads() {
7557 for (BuiltinCandidateTypeSet::iterator
7558 Ptr = CandidateTypes[0].pointer_begin(),
7559 PtrEnd = CandidateTypes[0].pointer_end();
7560 Ptr != PtrEnd; ++Ptr) {
7561 QualType C1Ty = (*Ptr);
7562 QualType C1;
7563 QualifierCollector Q1;
7564 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7565 if (!isa<RecordType>(C1))
7566 continue;
7567 // heuristic to reduce number of builtin candidates in the set.
7568 // Add volatile/restrict version only if there are conversions to a
7569 // volatile/restrict type.
7570 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7571 continue;
7572 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7573 continue;
7574 for (BuiltinCandidateTypeSet::iterator
7575 MemPtr = CandidateTypes[1].member_pointer_begin(),
7576 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7577 MemPtr != MemPtrEnd; ++MemPtr) {
7578 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7579 QualType C2 = QualType(mptr->getClass(), 0);
7580 C2 = C2.getUnqualifiedType();
7581 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7582 break;
7583 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7584 // build CV12 T&
7585 QualType T = mptr->getPointeeType();
7586 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7587 T.isVolatileQualified())
7588 continue;
7589 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7590 T.isRestrictQualified())
7591 continue;
7592 T = Q1.apply(S.Context, T);
7593 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smith958ba642013-05-05 15:51:06 +00007594 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007595 }
7596 }
7597 }
7598
7599 // Note that we don't consider the first argument, since it has been
7600 // contextually converted to bool long ago. The candidates below are
7601 // therefore added as binary.
7602 //
7603 // C++ [over.built]p25:
7604 // For every type T, where T is a pointer, pointer-to-member, or scoped
7605 // enumeration type, there exist candidate operator functions of the form
7606 //
7607 // T operator?(bool, T, T);
7608 //
7609 void addConditionalOperatorOverloads() {
7610 /// Set of (canonical) types that we've already handled.
7611 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7612
7613 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7614 for (BuiltinCandidateTypeSet::iterator
7615 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7616 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7617 Ptr != PtrEnd; ++Ptr) {
7618 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7619 continue;
7620
7621 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smith958ba642013-05-05 15:51:06 +00007622 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007623 }
7624
7625 for (BuiltinCandidateTypeSet::iterator
7626 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7627 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7628 MemPtr != MemPtrEnd; ++MemPtr) {
7629 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7630 continue;
7631
7632 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smith958ba642013-05-05 15:51:06 +00007633 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007634 }
7635
Richard Smith80ad52f2013-01-02 11:42:31 +00007636 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007637 for (BuiltinCandidateTypeSet::iterator
7638 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7639 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7640 Enum != EnumEnd; ++Enum) {
7641 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7642 continue;
7643
7644 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7645 continue;
7646
7647 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smith958ba642013-05-05 15:51:06 +00007648 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007649 }
7650 }
7651 }
7652 }
7653};
7654
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007655} // end anonymous namespace
7656
7657/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7658/// operator overloads to the candidate set (C++ [over.built]), based
7659/// on the operator @p Op and the arguments given. For example, if the
7660/// operator is a binary '+', this routine might add "int
7661/// operator+(int, int)" to cover integer addition.
Robert Wilhelm834c0582013-08-09 18:02:13 +00007662void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7663 SourceLocation OpLoc,
7664 ArrayRef<Expr *> Args,
7665 OverloadCandidateSet &CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007666 // Find all of the types that the arguments can convert to, but only
7667 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00007668 // that make use of these types. Also record whether we encounter non-record
7669 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00007670 Qualifiers VisibleTypeConversionsQuals;
7671 VisibleTypeConversionsQuals.addConst();
Richard Smith958ba642013-05-05 15:51:06 +00007672 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanian8621d012009-10-19 21:30:45 +00007673 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00007674
7675 bool HasNonRecordCandidateType = false;
7676 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00007677 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smith958ba642013-05-05 15:51:06 +00007678 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorfec56e72010-11-03 17:00:07 +00007679 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7680 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7681 OpLoc,
7682 true,
7683 (Op == OO_Exclaim ||
7684 Op == OO_AmpAmp ||
7685 Op == OO_PipePipe),
7686 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00007687 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7688 CandidateTypes[ArgIdx].hasNonRecordTypes();
7689 HasArithmeticOrEnumeralCandidateType =
7690 HasArithmeticOrEnumeralCandidateType ||
7691 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00007692 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007693
Chandler Carruth6a577462010-12-13 01:44:01 +00007694 // Exit early when no non-record types have been added to the candidate set
7695 // for any of the arguments to the operator.
Douglas Gregor25aaff92011-10-10 14:05:31 +00007696 //
7697 // We can't exit early for !, ||, or &&, since there we have always have
7698 // 'bool' overloads.
Richard Smith958ba642013-05-05 15:51:06 +00007699 if (!HasNonRecordCandidateType &&
Douglas Gregor25aaff92011-10-10 14:05:31 +00007700 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth6a577462010-12-13 01:44:01 +00007701 return;
7702
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007703 // Setup an object to manage the common state for building overloads.
Richard Smith958ba642013-05-05 15:51:06 +00007704 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007705 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00007706 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007707 CandidateTypes, CandidateSet);
7708
7709 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007710 switch (Op) {
7711 case OO_None:
7712 case NUM_OVERLOADED_OPERATORS:
David Blaikieb219cfc2011-09-23 05:06:16 +00007713 llvm_unreachable("Expected an overloaded operator");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007714
Chandler Carruthabb71842010-12-12 08:51:33 +00007715 case OO_New:
7716 case OO_Delete:
7717 case OO_Array_New:
7718 case OO_Array_Delete:
7719 case OO_Call:
David Blaikieb219cfc2011-09-23 05:06:16 +00007720 llvm_unreachable(
7721 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruthabb71842010-12-12 08:51:33 +00007722
7723 case OO_Comma:
7724 case OO_Arrow:
7725 // C++ [over.match.oper]p3:
7726 // -- For the operator ',', the unary operator '&', or the
7727 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00007728 break;
7729
7730 case OO_Plus: // '+' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007731 if (Args.size() == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007732 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007733 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00007734
7735 case OO_Minus: // '-' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007736 if (Args.size() == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007737 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007738 } else {
7739 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7740 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7741 }
Douglas Gregor74253732008-11-19 15:42:04 +00007742 break;
7743
Chandler Carruthabb71842010-12-12 08:51:33 +00007744 case OO_Star: // '*' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007745 if (Args.size() == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007746 OpBuilder.addUnaryStarPointerOverloads();
7747 else
7748 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7749 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007750
Chandler Carruthabb71842010-12-12 08:51:33 +00007751 case OO_Slash:
7752 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00007753 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007754
7755 case OO_PlusPlus:
7756 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007757 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7758 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00007759 break;
7760
Douglas Gregor19b7b152009-08-24 13:43:27 +00007761 case OO_EqualEqual:
7762 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007763 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007764 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00007765
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007766 case OO_Less:
7767 case OO_Greater:
7768 case OO_LessEqual:
7769 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007770 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007771 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7772 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007773
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007774 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007775 case OO_Caret:
7776 case OO_Pipe:
7777 case OO_LessLess:
7778 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007779 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007780 break;
7781
Chandler Carruthabb71842010-12-12 08:51:33 +00007782 case OO_Amp: // '&' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007783 if (Args.size() == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007784 // C++ [over.match.oper]p3:
7785 // -- For the operator ',', the unary operator '&', or the
7786 // operator '->', the built-in candidates set is empty.
7787 break;
7788
7789 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7790 break;
7791
7792 case OO_Tilde:
7793 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7794 break;
7795
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007796 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007797 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00007798 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007799
7800 case OO_PlusEqual:
7801 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007802 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007803 // Fall through.
7804
7805 case OO_StarEqual:
7806 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007807 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007808 break;
7809
7810 case OO_PercentEqual:
7811 case OO_LessLessEqual:
7812 case OO_GreaterGreaterEqual:
7813 case OO_AmpEqual:
7814 case OO_CaretEqual:
7815 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007816 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007817 break;
7818
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007819 case OO_Exclaim:
7820 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00007821 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007822
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007823 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007824 case OO_PipePipe:
7825 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007826 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007827
7828 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007829 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007830 break;
7831
7832 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007833 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007834 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007835
7836 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007837 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007838 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7839 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007840 }
7841}
7842
Douglas Gregorfa047642009-02-04 00:32:51 +00007843/// \brief Add function candidates found via argument-dependent lookup
7844/// to the set of overloading candidates.
7845///
7846/// This routine performs argument-dependent name lookup based on the
7847/// given function name (which may also be an operator name) and adds
7848/// all of the overload candidates found by ADL to the overload
7849/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00007850void
Douglas Gregorfa047642009-02-04 00:32:51 +00007851Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00007852 bool Operator, SourceLocation Loc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00007853 ArrayRef<Expr *> Args,
Douglas Gregor67714232011-03-03 02:41:12 +00007854 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007855 OverloadCandidateSet& CandidateSet,
Richard Smithb1502bc2012-10-18 17:56:02 +00007856 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00007857 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00007858
John McCalla113e722010-01-26 06:04:06 +00007859 // FIXME: This approach for uniquing ADL results (and removing
7860 // redundant candidates from the set) relies on pointer-equality,
7861 // which means we need to key off the canonical decl. However,
7862 // always going back to the canonical decl might not get us the
7863 // right set of default arguments. What default arguments are
7864 // we supposed to consider on ADL candidates, anyway?
7865
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007866 // FIXME: Pass in the explicit template arguments?
Richard Smithb1502bc2012-10-18 17:56:02 +00007867 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00007868
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007869 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007870 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7871 CandEnd = CandidateSet.end();
7872 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00007873 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00007874 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00007875 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00007876 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00007877 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007878
7879 // For each of the ADL candidates we found, add it to the overload
7880 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00007881 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00007882 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00007883 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00007884 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007885 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007886
Ahmed Charles13a140c2012-02-25 11:00:22 +00007887 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7888 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007889 } else
John McCall6e266892010-01-26 03:27:55 +00007890 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00007891 FoundDecl, ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00007892 Args, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00007893 }
Douglas Gregorfa047642009-02-04 00:32:51 +00007894}
7895
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007896/// isBetterOverloadCandidate - Determines whether the first overload
7897/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00007898bool
John McCall120d63c2010-08-24 20:38:10 +00007899isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00007900 const OverloadCandidate &Cand1,
7901 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007902 SourceLocation Loc,
7903 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007904 // Define viable functions to be better candidates than non-viable
7905 // functions.
7906 if (!Cand2.Viable)
7907 return Cand1.Viable;
7908 else if (!Cand1.Viable)
7909 return false;
7910
Douglas Gregor88a35142008-12-22 05:46:06 +00007911 // C++ [over.match.best]p1:
7912 //
7913 // -- if F is a static member function, ICS1(F) is defined such
7914 // that ICS1(F) is neither better nor worse than ICS1(G) for
7915 // any function G, and, symmetrically, ICS1(G) is neither
7916 // better nor worse than ICS1(F).
7917 unsigned StartArg = 0;
7918 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7919 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007920
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007921 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00007922 // A viable function F1 is defined to be a better function than another
7923 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007924 // conversion sequence than ICSi(F2), and then...
Benjamin Kramer09dd3792012-01-14 16:32:05 +00007925 unsigned NumArgs = Cand1.NumConversions;
7926 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007927 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00007928 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00007929 switch (CompareImplicitConversionSequences(S,
7930 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007931 Cand2.Conversions[ArgIdx])) {
7932 case ImplicitConversionSequence::Better:
7933 // Cand1 has a better conversion sequence.
7934 HasBetterConversion = true;
7935 break;
7936
7937 case ImplicitConversionSequence::Worse:
7938 // Cand1 can't be better than Cand2.
7939 return false;
7940
7941 case ImplicitConversionSequence::Indistinguishable:
7942 // Do nothing.
7943 break;
7944 }
7945 }
7946
Mike Stump1eb44332009-09-09 15:08:12 +00007947 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007948 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007949 if (HasBetterConversion)
7950 return true;
7951
Mike Stump1eb44332009-09-09 15:08:12 +00007952 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007953 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00007954 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007955 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7956 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00007957
7958 // -- F1 and F2 are function template specializations, and the function
7959 // template for F1 is more specialized than the template for F2
7960 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007961 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00007962 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregordfc331e2011-01-19 23:54:39 +00007963 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007964 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00007965 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7966 Cand2.Function->getPrimaryTemplate(),
7967 Loc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007968 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00007969 : TPOC_Call,
Richard Smith66118c22013-09-11 00:52:39 +00007970 Cand1.ExplicitCallArguments,
7971 Cand2.ExplicitCallArguments))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007972 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregordfc331e2011-01-19 23:54:39 +00007973 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007974
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007975 // -- the context is an initialization by user-defined conversion
7976 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7977 // from the return type of F1 to the destination type (i.e.,
7978 // the type of the entity being initialized) is a better
7979 // conversion sequence than the standard conversion sequence
7980 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007981 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00007982 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007983 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregorb734e242012-02-22 17:32:19 +00007984 // First check whether we prefer one of the conversion functions over the
7985 // other. This only distinguishes the results in non-standard, extension
7986 // cases such as the conversion from a lambda closure type to a function
7987 // pointer or block.
7988 ImplicitConversionSequence::CompareKind FuncResult
7989 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7990 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7991 return FuncResult;
7992
John McCall120d63c2010-08-24 20:38:10 +00007993 switch (CompareStandardConversionSequences(S,
7994 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007995 Cand2.FinalConversion)) {
7996 case ImplicitConversionSequence::Better:
7997 // Cand1 has a better conversion sequence.
7998 return true;
7999
8000 case ImplicitConversionSequence::Worse:
8001 // Cand1 can't be better than Cand2.
8002 return false;
8003
8004 case ImplicitConversionSequence::Indistinguishable:
8005 // Do nothing
8006 break;
8007 }
8008 }
8009
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008010 return false;
8011}
8012
Mike Stump1eb44332009-09-09 15:08:12 +00008013/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00008014/// within an overload candidate set.
8015///
James Dennettefce31f2012-06-22 08:10:18 +00008016/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregore0762c92009-06-19 23:52:42 +00008017/// which overload resolution occurs.
8018///
James Dennettefce31f2012-06-22 08:10:18 +00008019/// \param Best If overload resolution was successful or found a deleted
8020/// function, \p Best points to the candidate function found.
Douglas Gregore0762c92009-06-19 23:52:42 +00008021///
8022/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00008023OverloadingResult
8024OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00008025 iterator &Best,
Chandler Carruth25ca4212011-02-25 19:41:05 +00008026 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008027 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00008028 Best = end();
8029 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8030 if (Cand->Viable)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008031 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00008032 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008033 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008034 }
8035
8036 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00008037 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008038 return OR_No_Viable_Function;
8039
8040 // Make sure that this function is better than every other viable
8041 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00008042 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00008043 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008044 Cand != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008045 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00008046 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00008047 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008048 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008049 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008050 }
Mike Stump1eb44332009-09-09 15:08:12 +00008051
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008052 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008053 if (Best->Function &&
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008054 (Best->Function->isDeleted() ||
8055 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008056 return OR_Deleted;
8057
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008058 return OR_Success;
8059}
8060
John McCall3c80f572010-01-12 02:15:36 +00008061namespace {
8062
8063enum OverloadCandidateKind {
8064 oc_function,
8065 oc_method,
8066 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00008067 oc_function_template,
8068 oc_method_template,
8069 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00008070 oc_implicit_default_constructor,
8071 oc_implicit_copy_constructor,
Sean Hunt82713172011-05-25 23:16:36 +00008072 oc_implicit_move_constructor,
Sebastian Redlf677ea32011-02-05 19:23:19 +00008073 oc_implicit_copy_assignment,
Sean Hunt82713172011-05-25 23:16:36 +00008074 oc_implicit_move_assignment,
Sebastian Redlf677ea32011-02-05 19:23:19 +00008075 oc_implicit_inherited_constructor
John McCall3c80f572010-01-12 02:15:36 +00008076};
8077
John McCall220ccbf2010-01-13 00:25:19 +00008078OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8079 FunctionDecl *Fn,
8080 std::string &Description) {
8081 bool isTemplate = false;
8082
8083 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8084 isTemplate = true;
8085 Description = S.getTemplateArgumentBindingsText(
8086 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8087 }
John McCallb1622a12010-01-06 09:43:14 +00008088
8089 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00008090 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00008091 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00008092
Sebastian Redlf677ea32011-02-05 19:23:19 +00008093 if (Ctor->getInheritedConstructor())
8094 return oc_implicit_inherited_constructor;
8095
Sean Hunt82713172011-05-25 23:16:36 +00008096 if (Ctor->isDefaultConstructor())
8097 return oc_implicit_default_constructor;
8098
8099 if (Ctor->isMoveConstructor())
8100 return oc_implicit_move_constructor;
8101
8102 assert(Ctor->isCopyConstructor() &&
8103 "unexpected sort of implicit constructor");
8104 return oc_implicit_copy_constructor;
John McCallb1622a12010-01-06 09:43:14 +00008105 }
8106
8107 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8108 // This actually gets spelled 'candidate function' for now, but
8109 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00008110 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00008111 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00008112
Sean Hunt82713172011-05-25 23:16:36 +00008113 if (Meth->isMoveAssignmentOperator())
8114 return oc_implicit_move_assignment;
8115
Douglas Gregoref7d78b2012-02-10 08:36:38 +00008116 if (Meth->isCopyAssignmentOperator())
8117 return oc_implicit_copy_assignment;
8118
8119 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8120 return oc_method;
John McCall3c80f572010-01-12 02:15:36 +00008121 }
8122
John McCall220ccbf2010-01-13 00:25:19 +00008123 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00008124}
8125
Larisse Voufo43847122013-07-19 23:00:19 +00008126void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
Sebastian Redlf677ea32011-02-05 19:23:19 +00008127 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8128 if (!Ctor) return;
8129
8130 Ctor = Ctor->getInheritedConstructor();
8131 if (!Ctor) return;
8132
8133 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8134}
8135
John McCall3c80f572010-01-12 02:15:36 +00008136} // end anonymous namespace
8137
8138// Notes the location of an overload candidate.
Richard Trieu6efd4c52011-11-23 22:32:32 +00008139void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCall220ccbf2010-01-13 00:25:19 +00008140 std::string FnDesc;
8141 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieu6efd4c52011-11-23 22:32:32 +00008142 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8143 << (unsigned) K << FnDesc;
8144 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8145 Diag(Fn->getLocation(), PD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008146 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallb1622a12010-01-06 09:43:14 +00008147}
8148
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008149//Notes the location of all overload candidates designated through
8150// OverloadedExpr
Richard Trieu6efd4c52011-11-23 22:32:32 +00008151void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008152 assert(OverloadedExpr->getType() == Context.OverloadTy);
8153
8154 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8155 OverloadExpr *OvlExpr = Ovl.Expression;
8156
8157 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8158 IEnd = OvlExpr->decls_end();
8159 I != IEnd; ++I) {
8160 if (FunctionTemplateDecl *FunTmpl =
8161 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00008162 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008163 } else if (FunctionDecl *Fun
8164 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00008165 NoteOverloadCandidate(Fun, DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008166 }
8167 }
8168}
8169
John McCall1d318332010-01-12 00:44:57 +00008170/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8171/// "lead" diagnostic; it will be given two arguments, the source and
8172/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00008173void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8174 Sema &S,
8175 SourceLocation CaretLoc,
8176 const PartialDiagnostic &PDiag) const {
8177 S.Diag(CaretLoc, PDiag)
8178 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay45a37da2012-11-08 20:50:02 +00008179 // FIXME: The note limiting machinery is borrowed from
8180 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8181 // refactoring here.
8182 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8183 unsigned CandsShown = 0;
8184 AmbiguousConversionSequence::const_iterator I, E;
8185 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8186 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8187 break;
8188 ++CandsShown;
John McCall120d63c2010-08-24 20:38:10 +00008189 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00008190 }
Matt Beaumont-Gay45a37da2012-11-08 20:50:02 +00008191 if (I != E)
8192 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall81201622010-01-08 04:41:39 +00008193}
8194
John McCall1d318332010-01-12 00:44:57 +00008195namespace {
8196
John McCalladbb8f82010-01-13 09:16:55 +00008197void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8198 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8199 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00008200 assert(Cand->Function && "for now, candidate must be a function");
8201 FunctionDecl *Fn = Cand->Function;
8202
8203 // There's a conversion slot for the object argument if this is a
8204 // non-constructor method. Note that 'I' corresponds the
8205 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00008206 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00008207 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00008208 if (I == 0)
8209 isObjectArgument = true;
8210 else
8211 I--;
John McCall220ccbf2010-01-13 00:25:19 +00008212 }
8213
John McCall220ccbf2010-01-13 00:25:19 +00008214 std::string FnDesc;
8215 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8216
John McCalladbb8f82010-01-13 09:16:55 +00008217 Expr *FromExpr = Conv.Bad.FromExpr;
8218 QualType FromTy = Conv.Bad.getFromType();
8219 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00008220
John McCall5920dbb2010-02-02 02:42:52 +00008221 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00008222 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00008223 Expr *E = FromExpr->IgnoreParens();
8224 if (isa<UnaryOperator>(E))
8225 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00008226 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00008227
8228 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8229 << (unsigned) FnKind << FnDesc
8230 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8231 << ToTy << Name << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008232 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall5920dbb2010-02-02 02:42:52 +00008233 return;
8234 }
8235
John McCall258b2032010-01-23 08:10:49 +00008236 // Do some hand-waving analysis to see if the non-viability is due
8237 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00008238 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8239 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8240 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8241 CToTy = RT->getPointeeType();
8242 else {
8243 // TODO: detect and diagnose the full richness of const mismatches.
8244 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8245 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8246 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8247 }
8248
8249 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8250 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall651f3ee2010-01-14 03:28:57 +00008251 Qualifiers FromQs = CFromTy.getQualifiers();
8252 Qualifiers ToQs = CToTy.getQualifiers();
8253
8254 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8255 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8256 << (unsigned) FnKind << FnDesc
8257 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8258 << FromTy
8259 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8260 << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008261 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008262 return;
8263 }
8264
John McCallf85e1932011-06-15 23:02:42 +00008265 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00008266 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCallf85e1932011-06-15 23:02:42 +00008267 << (unsigned) FnKind << FnDesc
8268 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8269 << FromTy
8270 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8271 << (unsigned) isObjectArgument << I+1;
8272 MaybeEmitInheritedConstructorNote(S, Fn);
8273 return;
8274 }
8275
Douglas Gregor028ea4b2011-04-26 23:16:46 +00008276 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8277 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8278 << (unsigned) FnKind << FnDesc
8279 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8280 << FromTy
8281 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8282 << (unsigned) isObjectArgument << I+1;
8283 MaybeEmitInheritedConstructorNote(S, Fn);
8284 return;
8285 }
8286
John McCall651f3ee2010-01-14 03:28:57 +00008287 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8288 assert(CVR && "unexpected qualifiers mismatch");
8289
8290 if (isObjectArgument) {
8291 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8292 << (unsigned) FnKind << FnDesc
8293 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8294 << FromTy << (CVR - 1);
8295 } else {
8296 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8297 << (unsigned) FnKind << FnDesc
8298 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8299 << FromTy << (CVR - 1) << I+1;
8300 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008301 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008302 return;
8303 }
8304
Sebastian Redlfd2a00a2011-09-24 17:48:32 +00008305 // Special diagnostic for failure to convert an initializer list, since
8306 // telling the user that it has type void is not useful.
8307 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8308 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8309 << (unsigned) FnKind << FnDesc
8310 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8311 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8312 MaybeEmitInheritedConstructorNote(S, Fn);
8313 return;
8314 }
8315
John McCall258b2032010-01-23 08:10:49 +00008316 // Diagnose references or pointers to incomplete types differently,
8317 // since it's far from impossible that the incompleteness triggered
8318 // the failure.
8319 QualType TempFromTy = FromTy.getNonReferenceType();
8320 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8321 TempFromTy = PTy->getPointeeType();
8322 if (TempFromTy->isIncompleteType()) {
8323 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8324 << (unsigned) FnKind << FnDesc
8325 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8326 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008327 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall258b2032010-01-23 08:10:49 +00008328 return;
8329 }
8330
Douglas Gregor85789812010-06-30 23:01:39 +00008331 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008332 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00008333 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8334 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8335 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8336 FromPtrTy->getPointeeType()) &&
8337 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8338 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008339 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor85789812010-06-30 23:01:39 +00008340 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008341 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00008342 }
8343 } else if (const ObjCObjectPointerType *FromPtrTy
8344 = FromTy->getAs<ObjCObjectPointerType>()) {
8345 if (const ObjCObjectPointerType *ToPtrTy
8346 = ToTy->getAs<ObjCObjectPointerType>())
8347 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8348 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8349 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8350 FromPtrTy->getPointeeType()) &&
8351 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008352 BaseToDerivedConversion = 2;
8353 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008354 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8355 !FromTy->isIncompleteType() &&
8356 !ToRefTy->getPointeeType()->isIncompleteType() &&
8357 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8358 BaseToDerivedConversion = 3;
8359 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8360 ToTy.getNonReferenceType().getCanonicalType() ==
8361 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008362 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8363 << (unsigned) FnKind << FnDesc
8364 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8365 << (unsigned) isObjectArgument << I + 1;
8366 MaybeEmitInheritedConstructorNote(S, Fn);
8367 return;
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008368 }
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008369 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008370
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008371 if (BaseToDerivedConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008372 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008373 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00008374 << (unsigned) FnKind << FnDesc
8375 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008376 << (BaseToDerivedConversion - 1)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008377 << FromTy << ToTy << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008378 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor85789812010-06-30 23:01:39 +00008379 return;
8380 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008381
Fariborz Jahanian909bcb32011-07-20 17:14:09 +00008382 if (isa<ObjCObjectPointerType>(CFromTy) &&
8383 isa<PointerType>(CToTy)) {
8384 Qualifiers FromQs = CFromTy.getQualifiers();
8385 Qualifiers ToQs = CToTy.getQualifiers();
8386 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8387 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8388 << (unsigned) FnKind << FnDesc
8389 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8390 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8391 MaybeEmitInheritedConstructorNote(S, Fn);
8392 return;
8393 }
8394 }
8395
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008396 // Emit the generic diagnostic and, optionally, add the hints to it.
8397 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8398 FDiag << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00008399 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008400 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8401 << (unsigned) (Cand->Fix.Kind);
8402
8403 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer1136ef02012-01-14 21:05:10 +00008404 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8405 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008406 FDiag << *HI;
8407 S.Diag(Fn->getLocation(), FDiag);
8408
Sebastian Redlf677ea32011-02-05 19:23:19 +00008409 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalladbb8f82010-01-13 09:16:55 +00008410}
8411
Larisse Voufo43847122013-07-19 23:00:19 +00008412/// Additional arity mismatch diagnosis specific to a function overload
8413/// candidates. This is not covered by the more general DiagnoseArityMismatch()
8414/// over a candidate in any candidate set.
8415bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8416 unsigned NumArgs) {
John McCalladbb8f82010-01-13 09:16:55 +00008417 FunctionDecl *Fn = Cand->Function;
John McCalladbb8f82010-01-13 09:16:55 +00008418 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008419
Douglas Gregor439d3c32011-05-05 00:13:13 +00008420 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo43847122013-07-19 23:00:19 +00008421 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor439d3c32011-05-05 00:13:13 +00008422 // right number of arguments, because only overloaded operators have
8423 // the weird behavior of overloading member and non-member functions.
8424 // Just don't report anything.
8425 if (Fn->isInvalidDecl() &&
8426 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo43847122013-07-19 23:00:19 +00008427 return true;
8428
8429 if (NumArgs < MinParams) {
8430 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8431 (Cand->FailureKind == ovl_fail_bad_deduction &&
8432 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8433 } else {
8434 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8435 (Cand->FailureKind == ovl_fail_bad_deduction &&
8436 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8437 }
8438
8439 return false;
8440}
8441
8442/// General arity mismatch diagnosis over a candidate in a candidate set.
8443void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
8444 assert(isa<FunctionDecl>(D) &&
8445 "The templated declaration should at least be a function"
8446 " when diagnosing bad template argument deduction due to too many"
8447 " or too few arguments");
8448
8449 FunctionDecl *Fn = cast<FunctionDecl>(D);
8450
8451 // TODO: treat calls to a missing default constructor as a special case
8452 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8453 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor439d3c32011-05-05 00:13:13 +00008454
John McCalladbb8f82010-01-13 09:16:55 +00008455 // at least / at most / exactly
8456 unsigned mode, modeCount;
8457 if (NumFormalArgs < MinParams) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008458 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00008459 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00008460 mode = 0; // "at least"
8461 else
8462 mode = 2; // "exactly"
8463 modeCount = MinParams;
8464 } else {
John McCalladbb8f82010-01-13 09:16:55 +00008465 if (MinParams != FnTy->getNumArgs())
8466 mode = 1; // "at most"
8467 else
8468 mode = 2; // "exactly"
8469 modeCount = FnTy->getNumArgs();
8470 }
8471
8472 std::string Description;
8473 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8474
Richard Smithf7b80562012-05-11 05:16:41 +00008475 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8476 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8477 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8478 << Fn->getParamDecl(0) << NumFormalArgs;
8479 else
8480 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8481 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8482 << modeCount << NumFormalArgs;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008483 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008484}
8485
Larisse Voufo43847122013-07-19 23:00:19 +00008486/// Arity mismatch diagnosis specific to a function overload candidate.
8487void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8488 unsigned NumFormalArgs) {
8489 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
8490 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
8491}
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008492
Larisse Voufo43847122013-07-19 23:00:19 +00008493TemplateDecl *getDescribedTemplate(Decl *Templated) {
8494 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
8495 return FD->getDescribedFunctionTemplate();
8496 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
8497 return RD->getDescribedClassTemplate();
8498
8499 llvm_unreachable("Unsupported: Getting the described template declaration"
8500 " for bad deduction diagnosis");
8501}
8502
8503/// Diagnose a failed template-argument deduction.
8504void DiagnoseBadDeduction(Sema &S, Decl *Templated,
8505 DeductionFailureInfo &DeductionFailure,
8506 unsigned NumArgs) {
8507 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00008508 NamedDecl *ParamD;
8509 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8510 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8511 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo43847122013-07-19 23:00:19 +00008512 switch (DeductionFailure.Result) {
John McCall342fec42010-02-01 18:53:26 +00008513 case Sema::TDK_Success:
8514 llvm_unreachable("TDK_success while diagnosing bad deduction");
8515
8516 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00008517 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo43847122013-07-19 23:00:19 +00008518 S.Diag(Templated->getLocation(),
8519 diag::note_ovl_candidate_incomplete_deduction)
8520 << ParamD->getDeclName();
8521 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall342fec42010-02-01 18:53:26 +00008522 return;
8523 }
8524
John McCall57e97782010-08-05 09:05:08 +00008525 case Sema::TDK_Underqualified: {
8526 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8527 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8528
Larisse Voufo43847122013-07-19 23:00:19 +00008529 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall57e97782010-08-05 09:05:08 +00008530
8531 // Param will have been canonicalized, but it should just be a
8532 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00008533 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00008534 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00008535 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00008536 assert(S.Context.hasSameType(Param, NonCanonParam));
8537
8538 // Arg has also been canonicalized, but there's nothing we can do
8539 // about that. It also doesn't matter as much, because it won't
8540 // have any template parameters in it (because deduction isn't
8541 // done on dependent types).
Larisse Voufo43847122013-07-19 23:00:19 +00008542 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall57e97782010-08-05 09:05:08 +00008543
Larisse Voufo43847122013-07-19 23:00:19 +00008544 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
8545 << ParamD->getDeclName() << Arg << NonCanonParam;
8546 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall57e97782010-08-05 09:05:08 +00008547 return;
8548 }
8549
8550 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00008551 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00008552 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008553 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008554 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008555 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008556 which = 1;
8557 else {
Douglas Gregora9333192010-05-08 17:41:32 +00008558 which = 2;
8559 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008560
Larisse Voufo43847122013-07-19 23:00:19 +00008561 S.Diag(Templated->getLocation(),
8562 diag::note_ovl_candidate_inconsistent_deduction)
8563 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
8564 << *DeductionFailure.getSecondArg();
8565 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregora9333192010-05-08 17:41:32 +00008566 return;
8567 }
Douglas Gregora18592e2010-05-08 18:13:28 +00008568
Douglas Gregorf1a84452010-05-08 19:15:54 +00008569 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008570 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregorf1a84452010-05-08 19:15:54 +00008571 if (ParamD->getDeclName())
Larisse Voufo43847122013-07-19 23:00:19 +00008572 S.Diag(Templated->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008573 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo43847122013-07-19 23:00:19 +00008574 << ParamD->getDeclName();
Douglas Gregorf1a84452010-05-08 19:15:54 +00008575 else {
8576 int index = 0;
8577 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8578 index = TTP->getIndex();
8579 else if (NonTypeTemplateParmDecl *NTTP
8580 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8581 index = NTTP->getIndex();
8582 else
8583 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo43847122013-07-19 23:00:19 +00008584 S.Diag(Templated->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008585 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo43847122013-07-19 23:00:19 +00008586 << (index + 1);
Douglas Gregorf1a84452010-05-08 19:15:54 +00008587 }
Larisse Voufo43847122013-07-19 23:00:19 +00008588 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregorf1a84452010-05-08 19:15:54 +00008589 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008590
Douglas Gregora18592e2010-05-08 18:13:28 +00008591 case Sema::TDK_TooManyArguments:
8592 case Sema::TDK_TooFewArguments:
Larisse Voufo43847122013-07-19 23:00:19 +00008593 DiagnoseArityMismatch(S, Templated, NumArgs);
Douglas Gregora18592e2010-05-08 18:13:28 +00008594 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00008595
8596 case Sema::TDK_InstantiationDepth:
Larisse Voufo43847122013-07-19 23:00:19 +00008597 S.Diag(Templated->getLocation(),
8598 diag::note_ovl_candidate_instantiation_depth);
8599 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregorec20f462010-05-08 20:07:26 +00008600 return;
8601
8602 case Sema::TDK_SubstitutionFailure: {
Richard Smithb8590f32012-05-07 09:03:25 +00008603 // Format the template argument list into the argument string.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008604 SmallString<128> TemplateArgString;
Richard Smithb8590f32012-05-07 09:03:25 +00008605 if (TemplateArgumentList *Args =
Larisse Voufo43847122013-07-19 23:00:19 +00008606 DeductionFailure.getTemplateArgumentList()) {
Richard Smithb8590f32012-05-07 09:03:25 +00008607 TemplateArgString = " ";
8608 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo43847122013-07-19 23:00:19 +00008609 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smithb8590f32012-05-07 09:03:25 +00008610 }
8611
Richard Smith4493c0a2012-05-09 05:17:00 +00008612 // If this candidate was disabled by enable_if, say so.
Larisse Voufo43847122013-07-19 23:00:19 +00008613 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith4493c0a2012-05-09 05:17:00 +00008614 if (PDiag && PDiag->second.getDiagID() ==
8615 diag::err_typename_nested_not_found_enable_if) {
8616 // FIXME: Use the source range of the condition, and the fully-qualified
8617 // name of the enable_if template. These are both present in PDiag.
8618 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8619 << "'enable_if'" << TemplateArgString;
8620 return;
8621 }
8622
Richard Smithb8590f32012-05-07 09:03:25 +00008623 // Format the SFINAE diagnostic into the argument string.
8624 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8625 // formatted message in another diagnostic.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008626 SmallString<128> SFINAEArgString;
Richard Smithb8590f32012-05-07 09:03:25 +00008627 SourceRange R;
Richard Smith4493c0a2012-05-09 05:17:00 +00008628 if (PDiag) {
Richard Smithb8590f32012-05-07 09:03:25 +00008629 SFINAEArgString = ": ";
8630 R = SourceRange(PDiag->first, PDiag->first);
8631 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8632 }
8633
Larisse Voufo43847122013-07-19 23:00:19 +00008634 S.Diag(Templated->getLocation(),
8635 diag::note_ovl_candidate_substitution_failure)
8636 << TemplateArgString << SFINAEArgString << R;
8637 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregorec20f462010-05-08 20:07:26 +00008638 return;
8639 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008640
Richard Smith0efa62f2013-01-31 04:03:12 +00008641 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo43847122013-07-19 23:00:19 +00008642 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
8643 S.Diag(Templated->getLocation(),
Richard Smith0efa62f2013-01-31 04:03:12 +00008644 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo43847122013-07-19 23:00:19 +00008645 << R.Expression->getName();
Richard Smith0efa62f2013-01-31 04:03:12 +00008646 return;
8647 }
8648
Richard Trieueef35f82013-04-08 21:11:40 +00008649 case Sema::TDK_NonDeducedMismatch: {
Richard Smith29805ca2013-01-31 05:19:49 +00008650 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo43847122013-07-19 23:00:19 +00008651 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
8652 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieueef35f82013-04-08 21:11:40 +00008653 if (FirstTA.getKind() == TemplateArgument::Template &&
8654 SecondTA.getKind() == TemplateArgument::Template) {
8655 TemplateName FirstTN = FirstTA.getAsTemplate();
8656 TemplateName SecondTN = SecondTA.getAsTemplate();
8657 if (FirstTN.getKind() == TemplateName::Template &&
8658 SecondTN.getKind() == TemplateName::Template) {
8659 if (FirstTN.getAsTemplateDecl()->getName() ==
8660 SecondTN.getAsTemplateDecl()->getName()) {
8661 // FIXME: This fixes a bad diagnostic where both templates are named
8662 // the same. This particular case is a bit difficult since:
8663 // 1) It is passed as a string to the diagnostic printer.
8664 // 2) The diagnostic printer only attempts to find a better
8665 // name for types, not decls.
8666 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo43847122013-07-19 23:00:19 +00008667 S.Diag(Templated->getLocation(),
Richard Trieueef35f82013-04-08 21:11:40 +00008668 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
8669 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
8670 return;
8671 }
8672 }
8673 }
Larisse Voufo43847122013-07-19 23:00:19 +00008674 S.Diag(Templated->getLocation(),
8675 diag::note_ovl_candidate_non_deduced_mismatch)
8676 << FirstTA << SecondTA;
Richard Smith29805ca2013-01-31 05:19:49 +00008677 return;
Richard Trieueef35f82013-04-08 21:11:40 +00008678 }
John McCall342fec42010-02-01 18:53:26 +00008679 // TODO: diagnose these individually, then kill off
8680 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith29805ca2013-01-31 05:19:49 +00008681 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo43847122013-07-19 23:00:19 +00008682 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
8683 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall342fec42010-02-01 18:53:26 +00008684 return;
8685 }
8686}
8687
Larisse Voufo43847122013-07-19 23:00:19 +00008688/// Diagnose a failed template-argument deduction, for function calls.
8689void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, unsigned NumArgs) {
8690 unsigned TDK = Cand->DeductionFailure.Result;
8691 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
8692 if (CheckArityMismatch(S, Cand, NumArgs))
8693 return;
8694 }
8695 DiagnoseBadDeduction(S, Cand->Function, // pattern
8696 Cand->DeductionFailure, NumArgs);
8697}
8698
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008699/// CUDA: diagnose an invalid call across targets.
8700void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8701 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8702 FunctionDecl *Callee = Cand->Function;
8703
8704 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8705 CalleeTarget = S.IdentifyCUDATarget(Callee);
8706
8707 std::string FnDesc;
8708 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8709
8710 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8711 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8712}
8713
John McCall342fec42010-02-01 18:53:26 +00008714/// Generates a 'note' diagnostic for an overload candidate. We've
8715/// already generated a primary error at the call site.
8716///
8717/// It really does need to be a single diagnostic with its caret
8718/// pointed at the candidate declaration. Yes, this creates some
8719/// major challenges of technical writing. Yes, this makes pointing
8720/// out problems with specific arguments quite awkward. It's still
8721/// better than generating twenty screens of text for every failed
8722/// overload.
8723///
8724/// It would be great to be able to express per-candidate problems
8725/// more richly for those diagnostic clients that cared, but we'd
8726/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00008727void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008728 unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00008729 FunctionDecl *Fn = Cand->Function;
8730
John McCall81201622010-01-08 04:41:39 +00008731 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008732 if (Cand->Viable && (Fn->isDeleted() ||
8733 S.isFunctionConsideredUnavailable(Fn))) {
John McCall220ccbf2010-01-13 00:25:19 +00008734 std::string FnDesc;
8735 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00008736
8737 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith5bdaac52012-04-02 20:59:25 +00008738 << FnKind << FnDesc
8739 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008740 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalla1d7d622010-01-08 00:58:21 +00008741 return;
John McCall81201622010-01-08 04:41:39 +00008742 }
8743
John McCall220ccbf2010-01-13 00:25:19 +00008744 // We don't really have anything else to say about viable candidates.
8745 if (Cand->Viable) {
8746 S.NoteOverloadCandidate(Fn);
8747 return;
8748 }
John McCall1d318332010-01-12 00:44:57 +00008749
John McCalladbb8f82010-01-13 09:16:55 +00008750 switch (Cand->FailureKind) {
8751 case ovl_fail_too_many_arguments:
8752 case ovl_fail_too_few_arguments:
8753 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00008754
John McCalladbb8f82010-01-13 09:16:55 +00008755 case ovl_fail_bad_deduction:
Ahmed Charles13a140c2012-02-25 11:00:22 +00008756 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall342fec42010-02-01 18:53:26 +00008757
John McCall717e8912010-01-23 05:17:32 +00008758 case ovl_fail_trivial_conversion:
8759 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00008760 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00008761 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008762
John McCallb1bdc622010-02-25 01:37:24 +00008763 case ovl_fail_bad_conversion: {
8764 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008765 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00008766 if (Cand->Conversions[I].isBad())
8767 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008768
John McCalladbb8f82010-01-13 09:16:55 +00008769 // FIXME: this currently happens when we're called from SemaInit
8770 // when user-conversion overload fails. Figure out how to handle
8771 // those conditions and diagnose them well.
8772 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008773 }
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008774
8775 case ovl_fail_bad_target:
8776 return DiagnoseBadTarget(S, Cand);
John McCallb1bdc622010-02-25 01:37:24 +00008777 }
John McCalla1d7d622010-01-08 00:58:21 +00008778}
8779
8780void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8781 // Desugar the type of the surrogate down to a function type,
8782 // retaining as many typedefs as possible while still showing
8783 // the function type (and, therefore, its parameter types).
8784 QualType FnType = Cand->Surrogate->getConversionType();
8785 bool isLValueReference = false;
8786 bool isRValueReference = false;
8787 bool isPointer = false;
8788 if (const LValueReferenceType *FnTypeRef =
8789 FnType->getAs<LValueReferenceType>()) {
8790 FnType = FnTypeRef->getPointeeType();
8791 isLValueReference = true;
8792 } else if (const RValueReferenceType *FnTypeRef =
8793 FnType->getAs<RValueReferenceType>()) {
8794 FnType = FnTypeRef->getPointeeType();
8795 isRValueReference = true;
8796 }
8797 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8798 FnType = FnTypePtr->getPointeeType();
8799 isPointer = true;
8800 }
8801 // Desugar down to a function type.
8802 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8803 // Reconstruct the pointer/reference as appropriate.
8804 if (isPointer) FnType = S.Context.getPointerType(FnType);
8805 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8806 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8807
8808 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8809 << FnType;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008810 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalla1d7d622010-01-08 00:58:21 +00008811}
8812
8813void NoteBuiltinOperatorCandidate(Sema &S,
David Blaikie0bea8632012-10-08 01:11:04 +00008814 StringRef Opc,
John McCalla1d7d622010-01-08 00:58:21 +00008815 SourceLocation OpLoc,
8816 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008817 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalla1d7d622010-01-08 00:58:21 +00008818 std::string TypeStr("operator");
8819 TypeStr += Opc;
8820 TypeStr += "(";
8821 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008822 if (Cand->NumConversions == 1) {
John McCalla1d7d622010-01-08 00:58:21 +00008823 TypeStr += ")";
8824 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8825 } else {
8826 TypeStr += ", ";
8827 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8828 TypeStr += ")";
8829 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8830 }
8831}
8832
8833void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8834 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008835 unsigned NoOperands = Cand->NumConversions;
John McCalla1d7d622010-01-08 00:58:21 +00008836 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8837 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00008838 if (ICS.isBad()) break; // all meaningless after first invalid
8839 if (!ICS.isAmbiguous()) continue;
8840
John McCall120d63c2010-08-24 20:38:10 +00008841 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008842 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00008843 }
8844}
8845
Larisse Voufo43847122013-07-19 23:00:19 +00008846static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall1b77e732010-01-15 23:32:50 +00008847 if (Cand->Function)
8848 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00008849 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00008850 return Cand->Surrogate->getLocation();
8851 return SourceLocation();
8852}
8853
Larisse Voufo43847122013-07-19 23:00:19 +00008854static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth78bf6802011-09-10 00:51:24 +00008855 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008856 case Sema::TDK_Success:
David Blaikieb219cfc2011-09-23 05:06:16 +00008857 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008858
Douglas Gregorae19fbb2012-09-13 21:01:57 +00008859 case Sema::TDK_Invalid:
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008860 case Sema::TDK_Incomplete:
8861 return 1;
8862
8863 case Sema::TDK_Underqualified:
8864 case Sema::TDK_Inconsistent:
8865 return 2;
8866
8867 case Sema::TDK_SubstitutionFailure:
8868 case Sema::TDK_NonDeducedMismatch:
Richard Smith29805ca2013-01-31 05:19:49 +00008869 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008870 return 3;
8871
8872 case Sema::TDK_InstantiationDepth:
8873 case Sema::TDK_FailedOverloadResolution:
8874 return 4;
8875
8876 case Sema::TDK_InvalidExplicitArguments:
8877 return 5;
8878
8879 case Sema::TDK_TooManyArguments:
8880 case Sema::TDK_TooFewArguments:
8881 return 6;
8882 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008883 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008884}
8885
John McCallbf65c0b2010-01-12 00:48:53 +00008886struct CompareOverloadCandidatesForDisplay {
8887 Sema &S;
8888 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00008889
8890 bool operator()(const OverloadCandidate *L,
8891 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00008892 // Fast-path this check.
8893 if (L == R) return false;
8894
John McCall81201622010-01-08 04:41:39 +00008895 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00008896 if (L->Viable) {
8897 if (!R->Viable) return true;
8898
8899 // TODO: introduce a tri-valued comparison for overload
8900 // candidates. Would be more worthwhile if we had a sort
8901 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00008902 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8903 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00008904 } else if (R->Viable)
8905 return false;
John McCall81201622010-01-08 04:41:39 +00008906
John McCall1b77e732010-01-15 23:32:50 +00008907 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00008908
John McCall1b77e732010-01-15 23:32:50 +00008909 // Criteria by which we can sort non-viable candidates:
8910 if (!L->Viable) {
8911 // 1. Arity mismatches come after other candidates.
8912 if (L->FailureKind == ovl_fail_too_many_arguments ||
8913 L->FailureKind == ovl_fail_too_few_arguments)
8914 return false;
8915 if (R->FailureKind == ovl_fail_too_many_arguments ||
8916 R->FailureKind == ovl_fail_too_few_arguments)
8917 return true;
John McCall81201622010-01-08 04:41:39 +00008918
John McCall717e8912010-01-23 05:17:32 +00008919 // 2. Bad conversions come first and are ordered by the number
8920 // of bad conversions and quality of good conversions.
8921 if (L->FailureKind == ovl_fail_bad_conversion) {
8922 if (R->FailureKind != ovl_fail_bad_conversion)
8923 return true;
8924
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008925 // The conversion that can be fixed with a smaller number of changes,
8926 // comes first.
8927 unsigned numLFixes = L->Fix.NumConversionsFixed;
8928 unsigned numRFixes = R->Fix.NumConversionsFixed;
8929 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8930 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008931 if (numLFixes != numRFixes) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008932 if (numLFixes < numRFixes)
8933 return true;
8934 else
8935 return false;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008936 }
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008937
John McCall717e8912010-01-23 05:17:32 +00008938 // If there's any ordering between the defined conversions...
8939 // FIXME: this might not be transitive.
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008940 assert(L->NumConversions == R->NumConversions);
John McCall717e8912010-01-23 05:17:32 +00008941
8942 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00008943 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008944 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00008945 switch (CompareImplicitConversionSequences(S,
8946 L->Conversions[I],
8947 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00008948 case ImplicitConversionSequence::Better:
8949 leftBetter++;
8950 break;
8951
8952 case ImplicitConversionSequence::Worse:
8953 leftBetter--;
8954 break;
8955
8956 case ImplicitConversionSequence::Indistinguishable:
8957 break;
8958 }
8959 }
8960 if (leftBetter > 0) return true;
8961 if (leftBetter < 0) return false;
8962
8963 } else if (R->FailureKind == ovl_fail_bad_conversion)
8964 return false;
8965
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008966 if (L->FailureKind == ovl_fail_bad_deduction) {
8967 if (R->FailureKind != ovl_fail_bad_deduction)
8968 return true;
8969
8970 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8971 return RankDeductionFailure(L->DeductionFailure)
Eli Friedmance1846e2011-10-14 23:10:30 +00008972 < RankDeductionFailure(R->DeductionFailure);
Eli Friedman1c522f72011-10-14 21:52:24 +00008973 } else if (R->FailureKind == ovl_fail_bad_deduction)
8974 return false;
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008975
John McCall1b77e732010-01-15 23:32:50 +00008976 // TODO: others?
8977 }
8978
8979 // Sort everything else by location.
8980 SourceLocation LLoc = GetLocationForCandidate(L);
8981 SourceLocation RLoc = GetLocationForCandidate(R);
8982
8983 // Put candidates without locations (e.g. builtins) at the end.
8984 if (LLoc.isInvalid()) return false;
8985 if (RLoc.isInvalid()) return true;
8986
8987 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00008988 }
8989};
8990
John McCall717e8912010-01-23 05:17:32 +00008991/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008992/// computes up to the first. Produces the FixIt set if possible.
John McCall717e8912010-01-23 05:17:32 +00008993void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008994 ArrayRef<Expr *> Args) {
John McCall717e8912010-01-23 05:17:32 +00008995 assert(!Cand->Viable);
8996
8997 // Don't do anything on failures other than bad conversion.
8998 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8999
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009000 // We only want the FixIts if all the arguments can be corrected.
9001 bool Unfixable = false;
Anna Zaksf3546ee2011-07-28 19:46:48 +00009002 // Use a implicit copy initialization to check conversion fixes.
9003 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009004
John McCall717e8912010-01-23 05:17:32 +00009005 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00009006 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00009007 unsigned ConvCount = Cand->NumConversions;
John McCall717e8912010-01-23 05:17:32 +00009008 while (true) {
9009 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9010 ConvIdx++;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009011 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaksf3546ee2011-07-28 19:46:48 +00009012 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCall717e8912010-01-23 05:17:32 +00009013 break;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009014 }
John McCall717e8912010-01-23 05:17:32 +00009015 }
9016
9017 if (ConvIdx == ConvCount)
9018 return;
9019
John McCallb1bdc622010-02-25 01:37:24 +00009020 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9021 "remaining conversion is initialized?");
9022
Douglas Gregor23ef6c02010-04-16 17:45:54 +00009023 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00009024 // operation somehow.
9025 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00009026
9027 const FunctionProtoType* Proto;
9028 unsigned ArgIdx = ConvIdx;
9029
9030 if (Cand->IsSurrogate) {
9031 QualType ConvType
9032 = Cand->Surrogate->getConversionType().getNonReferenceType();
9033 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9034 ConvType = ConvPtrType->getPointeeType();
9035 Proto = ConvType->getAs<FunctionProtoType>();
9036 ArgIdx--;
9037 } else if (Cand->Function) {
9038 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9039 if (isa<CXXMethodDecl>(Cand->Function) &&
9040 !isa<CXXConstructorDecl>(Cand->Function))
9041 ArgIdx--;
9042 } else {
9043 // Builtin binary operator with a bad first conversion.
9044 assert(ConvCount <= 3);
9045 for (; ConvIdx != ConvCount; ++ConvIdx)
9046 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00009047 = TryCopyInitialization(S, Args[ConvIdx],
9048 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009049 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00009050 /*InOverloadResolution*/ true,
9051 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00009052 S.getLangOpts().ObjCAutoRefCount);
John McCall717e8912010-01-23 05:17:32 +00009053 return;
9054 }
9055
9056 // Fill in the rest of the conversions.
9057 unsigned NumArgsInProto = Proto->getNumArgs();
9058 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009059 if (ArgIdx < NumArgsInProto) {
John McCall717e8912010-01-23 05:17:32 +00009060 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00009061 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009062 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00009063 /*InOverloadResolution=*/true,
9064 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00009065 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009066 // Store the FixIt in the candidate if it exists.
9067 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaksf3546ee2011-07-28 19:46:48 +00009068 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009069 }
John McCall717e8912010-01-23 05:17:32 +00009070 else
9071 Cand->Conversions[ConvIdx].setEllipsis();
9072 }
9073}
9074
John McCalla1d7d622010-01-08 00:58:21 +00009075} // end anonymous namespace
9076
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00009077/// PrintOverloadCandidates - When overload resolution fails, prints
9078/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00009079/// set.
John McCall120d63c2010-08-24 20:38:10 +00009080void OverloadCandidateSet::NoteCandidates(Sema &S,
9081 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009082 ArrayRef<Expr *> Args,
David Blaikie0bea8632012-10-08 01:11:04 +00009083 StringRef Opc,
John McCall120d63c2010-08-24 20:38:10 +00009084 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00009085 // Sort the candidates by viability and position. Sorting directly would
9086 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00009087 SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00009088 if (OCD == OCD_AllCandidates) Cands.reserve(size());
9089 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00009090 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00009091 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00009092 else if (OCD == OCD_AllCandidates) {
Ahmed Charles13a140c2012-02-25 11:00:22 +00009093 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009094 if (Cand->Function || Cand->IsSurrogate)
9095 Cands.push_back(Cand);
9096 // Otherwise, this a non-viable builtin candidate. We do not, in general,
9097 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00009098 }
9099 }
9100
John McCallbf65c0b2010-01-12 00:48:53 +00009101 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00009102 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009103
John McCall1d318332010-01-12 00:44:57 +00009104 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00009105
Chris Lattner5f9e2722011-07-23 10:55:15 +00009106 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregordc7b6412012-10-23 23:11:23 +00009107 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009108 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00009109 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9110 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00009111
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009112 // Set an arbitrary limit on the number of candidate functions we'll spam
9113 // the user with. FIXME: This limit should depend on details of the
9114 // candidate list.
Douglas Gregordc7b6412012-10-23 23:11:23 +00009115 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009116 break;
9117 }
9118 ++CandsShown;
9119
John McCalla1d7d622010-01-08 00:58:21 +00009120 if (Cand->Function)
Ahmed Charles13a140c2012-02-25 11:00:22 +00009121 NoteFunctionCandidate(S, Cand, Args.size());
John McCalla1d7d622010-01-08 00:58:21 +00009122 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00009123 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009124 else {
9125 assert(Cand->Viable &&
9126 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00009127 // Generally we only see ambiguities including viable builtin
9128 // operators if overload resolution got screwed up by an
9129 // ambiguous user-defined conversion.
9130 //
9131 // FIXME: It's quite possible for different conversions to see
9132 // different ambiguities, though.
9133 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00009134 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00009135 ReportedAmbiguousConversions = true;
9136 }
John McCalla1d7d622010-01-08 00:58:21 +00009137
John McCall1d318332010-01-12 00:44:57 +00009138 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00009139 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00009140 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00009141 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009142
9143 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00009144 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00009145}
9146
Larisse Voufo43847122013-07-19 23:00:19 +00009147static SourceLocation
9148GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9149 return Cand->Specialization ? Cand->Specialization->getLocation()
9150 : SourceLocation();
9151}
9152
9153struct CompareTemplateSpecCandidatesForDisplay {
9154 Sema &S;
9155 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9156
9157 bool operator()(const TemplateSpecCandidate *L,
9158 const TemplateSpecCandidate *R) {
9159 // Fast-path this check.
9160 if (L == R)
9161 return false;
9162
9163 // Assuming that both candidates are not matches...
9164
9165 // Sort by the ranking of deduction failures.
9166 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9167 return RankDeductionFailure(L->DeductionFailure) <
9168 RankDeductionFailure(R->DeductionFailure);
9169
9170 // Sort everything else by location.
9171 SourceLocation LLoc = GetLocationForCandidate(L);
9172 SourceLocation RLoc = GetLocationForCandidate(R);
9173
9174 // Put candidates without locations (e.g. builtins) at the end.
9175 if (LLoc.isInvalid())
9176 return false;
9177 if (RLoc.isInvalid())
9178 return true;
9179
9180 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9181 }
9182};
9183
9184/// Diagnose a template argument deduction failure.
9185/// We are treating these failures as overload failures due to bad
9186/// deductions.
9187void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9188 DiagnoseBadDeduction(S, Specialization, // pattern
9189 DeductionFailure, /*NumArgs=*/0);
9190}
9191
9192void TemplateSpecCandidateSet::destroyCandidates() {
9193 for (iterator i = begin(), e = end(); i != e; ++i) {
9194 i->DeductionFailure.Destroy();
9195 }
9196}
9197
9198void TemplateSpecCandidateSet::clear() {
9199 destroyCandidates();
9200 Candidates.clear();
9201}
9202
9203/// NoteCandidates - When no template specialization match is found, prints
9204/// diagnostic messages containing the non-matching specializations that form
9205/// the candidate set.
9206/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9207/// OCD == OCD_AllCandidates and Cand->Viable == false.
9208void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9209 // Sort the candidates by position (assuming no candidate is a match).
9210 // Sorting directly would be prohibitive, so we make a set of pointers
9211 // and sort those.
9212 SmallVector<TemplateSpecCandidate *, 32> Cands;
9213 Cands.reserve(size());
9214 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9215 if (Cand->Specialization)
9216 Cands.push_back(Cand);
9217 // Otherwise, this is a non matching builtin candidate. We do not,
9218 // in general, want to list every possible builtin candidate.
9219 }
9220
9221 std::sort(Cands.begin(), Cands.end(),
9222 CompareTemplateSpecCandidatesForDisplay(S));
9223
9224 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9225 // for generalization purposes (?).
9226 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9227
9228 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9229 unsigned CandsShown = 0;
9230 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9231 TemplateSpecCandidate *Cand = *I;
9232
9233 // Set an arbitrary limit on the number of candidates we'll spam
9234 // the user with. FIXME: This limit should depend on details of the
9235 // candidate list.
9236 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9237 break;
9238 ++CandsShown;
9239
9240 assert(Cand->Specialization &&
9241 "Non-matching built-in candidates are not added to Cands.");
9242 Cand->NoteDeductionFailure(S);
9243 }
9244
9245 if (I != E)
9246 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9247}
9248
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009249// [PossiblyAFunctionType] --> [Return]
9250// NonFunctionType --> NonFunctionType
9251// R (A) --> R(A)
9252// R (*)(A) --> R (A)
9253// R (&)(A) --> R (A)
9254// R (S::*)(A) --> R (A)
9255QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9256 QualType Ret = PossiblyAFunctionType;
9257 if (const PointerType *ToTypePtr =
9258 PossiblyAFunctionType->getAs<PointerType>())
9259 Ret = ToTypePtr->getPointeeType();
9260 else if (const ReferenceType *ToTypeRef =
9261 PossiblyAFunctionType->getAs<ReferenceType>())
9262 Ret = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00009263 else if (const MemberPointerType *MemTypePtr =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009264 PossiblyAFunctionType->getAs<MemberPointerType>())
9265 Ret = MemTypePtr->getPointeeType();
9266 Ret =
9267 Context.getCanonicalType(Ret).getUnqualifiedType();
9268 return Ret;
9269}
Douglas Gregor904eed32008-11-10 20:40:00 +00009270
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009271// A helper class to help with address of function resolution
9272// - allows us to avoid passing around all those ugly parameters
9273class AddressOfFunctionResolver
9274{
9275 Sema& S;
9276 Expr* SourceExpr;
9277 const QualType& TargetType;
9278 QualType TargetFunctionType; // Extracted function type from target type
9279
9280 bool Complain;
9281 //DeclAccessPair& ResultFunctionAccessPair;
9282 ASTContext& Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009283
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009284 bool TargetTypeIsNonStaticMemberFunction;
9285 bool FoundNonTemplateFunction;
David Majnemer576a9af2013-08-01 06:13:59 +00009286 bool StaticMemberFunctionFromBoundPointer;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009287
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009288 OverloadExpr::FindResult OvlExprInfo;
9289 OverloadExpr *OvlExpr;
9290 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009291 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo43847122013-07-19 23:00:19 +00009292 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009293
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009294public:
Larisse Voufo43847122013-07-19 23:00:19 +00009295 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9296 const QualType &TargetType, bool Complain)
9297 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9298 Complain(Complain), Context(S.getASTContext()),
9299 TargetTypeIsNonStaticMemberFunction(
9300 !!TargetType->getAs<MemberPointerType>()),
9301 FoundNonTemplateFunction(false),
David Majnemer576a9af2013-08-01 06:13:59 +00009302 StaticMemberFunctionFromBoundPointer(false),
Larisse Voufo43847122013-07-19 23:00:19 +00009303 OvlExprInfo(OverloadExpr::find(SourceExpr)),
9304 OvlExpr(OvlExprInfo.Expression),
9305 FailedCandidates(OvlExpr->getNameLoc()) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009306 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruth90434232011-03-29 08:08:18 +00009307
David Majnemer576a9af2013-08-01 06:13:59 +00009308 if (TargetFunctionType->isFunctionType()) {
9309 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9310 if (!UME->isImplicitAccess() &&
9311 !S.ResolveSingleFunctionTemplateSpecialization(UME))
9312 StaticMemberFunctionFromBoundPointer = true;
9313 } else if (OvlExpr->hasExplicitTemplateArgs()) {
9314 DeclAccessPair dap;
9315 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9316 OvlExpr, false, &dap)) {
9317 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9318 if (!Method->isStatic()) {
9319 // If the target type is a non-function type and the function found
9320 // is a non-static member function, pretend as if that was the
9321 // target, it's the only possible type to end up with.
9322 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruth90434232011-03-29 08:08:18 +00009323
David Majnemer576a9af2013-08-01 06:13:59 +00009324 // And skip adding the function if its not in the proper form.
9325 // We'll diagnose this due to an empty set of functions.
9326 if (!OvlExprInfo.HasFormOfMemberPointer)
9327 return;
Chandler Carruth90434232011-03-29 08:08:18 +00009328 }
9329
David Majnemer576a9af2013-08-01 06:13:59 +00009330 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor83314aa2009-07-08 20:55:45 +00009331 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009332 return;
Douglas Gregor83314aa2009-07-08 20:55:45 +00009333 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009334
9335 if (OvlExpr->hasExplicitTemplateArgs())
9336 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00009337
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009338 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9339 // C++ [over.over]p4:
9340 // If more than one function is selected, [...]
9341 if (Matches.size() > 1) {
9342 if (FoundNonTemplateFunction)
9343 EliminateAllTemplateMatches();
9344 else
9345 EliminateAllExceptMostSpecializedTemplate();
9346 }
9347 }
9348 }
9349
9350private:
9351 bool isTargetTypeAFunction() const {
9352 return TargetFunctionType->isFunctionType();
9353 }
9354
9355 // [ToType] [Return]
9356
9357 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9358 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9359 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9360 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9361 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9362 }
9363
9364 // return true if any matching specializations were found
9365 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9366 const DeclAccessPair& CurAccessFunPair) {
9367 if (CXXMethodDecl *Method
9368 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9369 // Skip non-static function templates when converting to pointer, and
9370 // static when converting to member pointer.
9371 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9372 return false;
9373 }
9374 else if (TargetTypeIsNonStaticMemberFunction)
9375 return false;
9376
9377 // C++ [over.over]p2:
9378 // If the name is a function template, template argument deduction is
9379 // done (14.8.2.2), and if the argument deduction succeeds, the
9380 // resulting template argument list is used to generate a single
9381 // function template specialization, which is added to the set of
9382 // overloaded functions considered.
9383 FunctionDecl *Specialization = 0;
Larisse Voufo43847122013-07-19 23:00:19 +00009384 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009385 if (Sema::TemplateDeductionResult Result
9386 = S.DeduceTemplateArguments(FunctionTemplate,
9387 &OvlExplicitTemplateArgs,
9388 TargetFunctionType, Specialization,
Douglas Gregor092140a2013-04-17 08:45:07 +00009389 Info, /*InOverloadResolution=*/true)) {
Larisse Voufo43847122013-07-19 23:00:19 +00009390 // Make a note of the failed deduction for diagnostics.
9391 FailedCandidates.addCandidate()
9392 .set(FunctionTemplate->getTemplatedDecl(),
9393 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009394 return false;
9395 }
9396
Douglas Gregor092140a2013-04-17 08:45:07 +00009397 // Template argument deduction ensures that we have an exact match or
9398 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009399 // This function template specicalization works.
9400 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Douglas Gregor092140a2013-04-17 08:45:07 +00009401 assert(S.isSameOrCompatibleFunctionType(
9402 Context.getCanonicalType(Specialization->getType()),
9403 Context.getCanonicalType(TargetFunctionType)));
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009404 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9405 return true;
9406 }
9407
9408 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9409 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthbd647292009-12-29 06:17:27 +00009410 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00009411 // Skip non-static functions when converting to pointer, and static
9412 // when converting to member pointer.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009413 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9414 return false;
9415 }
9416 else if (TargetTypeIsNonStaticMemberFunction)
9417 return false;
Douglas Gregor904eed32008-11-10 20:40:00 +00009418
Chandler Carruthbd647292009-12-29 06:17:27 +00009419 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009420 if (S.getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00009421 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9422 if (S.CheckCUDATarget(Caller, FunDecl))
9423 return false;
9424
Richard Smith60e141e2013-05-04 07:00:32 +00009425 // If any candidate has a placeholder return type, trigger its deduction
9426 // now.
9427 if (S.getLangOpts().CPlusPlus1y &&
9428 FunDecl->getResultType()->isUndeducedType() &&
9429 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
9430 return false;
9431
Douglas Gregor43c79c22009-12-09 00:47:37 +00009432 QualType ResultTy;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009433 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9434 FunDecl->getType()) ||
Chandler Carruth18e04612011-06-18 01:19:03 +00009435 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9436 ResultTy)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009437 Matches.push_back(std::make_pair(CurAccessFunPair,
9438 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00009439 FoundNonTemplateFunction = true;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009440 return true;
Douglas Gregor00aeb522009-07-08 23:33:52 +00009441 }
Mike Stump1eb44332009-09-09 15:08:12 +00009442 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009443
9444 return false;
9445 }
9446
9447 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9448 bool Ret = false;
9449
9450 // If the overload expression doesn't have the form of a pointer to
9451 // member, don't try to convert it to a pointer-to-member type.
9452 if (IsInvalidFormOfPointerToMemberFunction())
9453 return false;
9454
9455 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9456 E = OvlExpr->decls_end();
9457 I != E; ++I) {
9458 // Look through any using declarations to find the underlying function.
9459 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9460
9461 // C++ [over.over]p3:
9462 // Non-member functions and static member functions match
9463 // targets of type "pointer-to-function" or "reference-to-function."
9464 // Nonstatic member functions match targets of
9465 // type "pointer-to-member-function."
9466 // Note that according to DR 247, the containing class does not matter.
9467 if (FunctionTemplateDecl *FunctionTemplate
9468 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9469 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9470 Ret = true;
9471 }
9472 // If we have explicit template arguments supplied, skip non-templates.
9473 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9474 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9475 Ret = true;
9476 }
9477 assert(Ret || Matches.empty());
9478 return Ret;
Douglas Gregor904eed32008-11-10 20:40:00 +00009479 }
9480
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009481 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00009482 // [...] and any given function template specialization F1 is
9483 // eliminated if the set contains a second function template
9484 // specialization whose function template is more specialized
9485 // than the function template of F1 according to the partial
9486 // ordering rules of 14.5.5.2.
9487
9488 // The algorithm specified above is quadratic. We instead use a
9489 // two-pass algorithm (similar to the one used to identify the
9490 // best viable function in an overload set) that identifies the
9491 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00009492
9493 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9494 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9495 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009496
Larisse Voufo43847122013-07-19 23:00:19 +00009497 // TODO: It looks like FailedCandidates does not serve much purpose
9498 // here, since the no_viable diagnostic has index 0.
9499 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith4ad09e62013-09-10 22:59:25 +00009500 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo43847122013-07-19 23:00:19 +00009501 SourceExpr->getLocStart(), S.PDiag(),
9502 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
9503 .second->getDeclName(),
9504 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
9505 Complain, TargetFunctionType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009506
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009507 if (Result != MatchesCopy.end()) {
9508 // Make it the first and only element
9509 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9510 Matches[0].second = cast<FunctionDecl>(*Result);
9511 Matches.resize(1);
John McCallc373d482010-01-27 01:50:18 +00009512 }
9513 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009514
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009515 void EliminateAllTemplateMatches() {
9516 // [...] any function template specializations in the set are
9517 // eliminated if the set also contains a non-template function, [...]
9518 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9519 if (Matches[I].second->getPrimaryTemplate() == 0)
9520 ++I;
9521 else {
9522 Matches[I] = Matches[--N];
9523 Matches.set_size(N);
9524 }
9525 }
9526 }
9527
9528public:
9529 void ComplainNoMatchesFound() const {
9530 assert(Matches.empty());
9531 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9532 << OvlExpr->getName() << TargetFunctionType
9533 << OvlExpr->getSourceRange();
Richard Smith72a36a12013-08-14 00:00:44 +00009534 if (FailedCandidates.empty())
9535 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9536 else {
9537 // We have some deduction failure messages. Use them to diagnose
9538 // the function templates, and diagnose the non-template candidates
9539 // normally.
9540 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9541 IEnd = OvlExpr->decls_end();
9542 I != IEnd; ++I)
9543 if (FunctionDecl *Fun =
9544 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
9545 S.NoteOverloadCandidate(Fun, TargetFunctionType);
9546 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
9547 }
9548 }
9549
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009550 bool IsInvalidFormOfPointerToMemberFunction() const {
9551 return TargetTypeIsNonStaticMemberFunction &&
9552 !OvlExprInfo.HasFormOfMemberPointer;
9553 }
David Majnemer576a9af2013-08-01 06:13:59 +00009554
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009555 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9556 // TODO: Should we condition this on whether any functions might
9557 // have matched, or is it more appropriate to do that in callers?
9558 // TODO: a fixit wouldn't hurt.
9559 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9560 << TargetType << OvlExpr->getSourceRange();
9561 }
David Majnemer576a9af2013-08-01 06:13:59 +00009562
9563 bool IsStaticMemberFunctionFromBoundPointer() const {
9564 return StaticMemberFunctionFromBoundPointer;
9565 }
9566
9567 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
9568 S.Diag(OvlExpr->getLocStart(),
9569 diag::err_invalid_form_pointer_member_function)
9570 << OvlExpr->getSourceRange();
9571 }
9572
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009573 void ComplainOfInvalidConversion() const {
9574 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9575 << OvlExpr->getName() << TargetType;
9576 }
9577
9578 void ComplainMultipleMatchesFound() const {
9579 assert(Matches.size() > 1);
9580 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9581 << OvlExpr->getName()
9582 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009583 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009584 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009585
9586 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9587
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009588 int getNumMatches() const { return Matches.size(); }
9589
9590 FunctionDecl* getMatchingFunctionDecl() const {
9591 if (Matches.size() != 1) return 0;
9592 return Matches[0].second;
9593 }
9594
9595 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9596 if (Matches.size() != 1) return 0;
9597 return &Matches[0].first;
9598 }
9599};
9600
9601/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9602/// an overloaded function (C++ [over.over]), where @p From is an
9603/// expression with overloaded function type and @p ToType is the type
9604/// we're trying to resolve to. For example:
9605///
9606/// @code
9607/// int f(double);
9608/// int f(int);
9609///
9610/// int (*pfd)(double) = f; // selects f(double)
9611/// @endcode
9612///
9613/// This routine returns the resulting FunctionDecl if it could be
9614/// resolved, and NULL otherwise. When @p Complain is true, this
9615/// routine will emit diagnostics if there is an error.
9616FunctionDecl *
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009617Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9618 QualType TargetType,
9619 bool Complain,
9620 DeclAccessPair &FoundResult,
9621 bool *pHadMultipleCandidates) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009622 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009623
9624 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9625 Complain);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009626 int NumMatches = Resolver.getNumMatches();
9627 FunctionDecl* Fn = 0;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009628 if (NumMatches == 0 && Complain) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009629 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9630 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9631 else
9632 Resolver.ComplainNoMatchesFound();
9633 }
9634 else if (NumMatches > 1 && Complain)
9635 Resolver.ComplainMultipleMatchesFound();
9636 else if (NumMatches == 1) {
9637 Fn = Resolver.getMatchingFunctionDecl();
9638 assert(Fn);
9639 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemer576a9af2013-08-01 06:13:59 +00009640 if (Complain) {
9641 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
9642 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
9643 else
9644 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
9645 }
Sebastian Redl07ab2022009-10-17 21:12:09 +00009646 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009647
9648 if (pHadMultipleCandidates)
9649 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009650 return Fn;
Douglas Gregor904eed32008-11-10 20:40:00 +00009651}
9652
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009653/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor4b52e252009-12-21 23:17:24 +00009654/// resolve that overloaded function expression down to a single function.
9655///
9656/// This routine can only resolve template-ids that refer to a single function
9657/// template, where that template-id refers to a single template whose template
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009658/// arguments are either provided by the template-id or have defaults,
Douglas Gregor4b52e252009-12-21 23:17:24 +00009659/// as described in C++0x [temp.arg.explicit]p3.
John McCall864c0412011-04-26 20:42:42 +00009660FunctionDecl *
9661Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9662 bool Complain,
9663 DeclAccessPair *FoundResult) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009664 // C++ [over.over]p1:
9665 // [...] [Note: any redundant set of parentheses surrounding the
9666 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00009667 // C++ [over.over]p1:
9668 // [...] The overloaded function name can be preceded by the &
9669 // operator.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009670
Douglas Gregor4b52e252009-12-21 23:17:24 +00009671 // If we didn't actually find any template-ids, we're done.
John McCall864c0412011-04-26 20:42:42 +00009672 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00009673 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00009674
9675 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall864c0412011-04-26 20:42:42 +00009676 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Larisse Voufo43847122013-07-19 23:00:19 +00009677 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009678
Douglas Gregor4b52e252009-12-21 23:17:24 +00009679 // Look through all of the overloaded functions, searching for one
9680 // whose type matches exactly.
9681 FunctionDecl *Matched = 0;
John McCall864c0412011-04-26 20:42:42 +00009682 for (UnresolvedSetIterator I = ovl->decls_begin(),
9683 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009684 // C++0x [temp.arg.explicit]p3:
9685 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009686 // where deduction is not done, if a template argument list is
9687 // specified and it, along with any default template arguments,
9688 // identifies a single function template specialization, then the
Douglas Gregor4b52e252009-12-21 23:17:24 +00009689 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00009690 FunctionTemplateDecl *FunctionTemplate
9691 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009692
Douglas Gregor4b52e252009-12-21 23:17:24 +00009693 // C++ [over.over]p2:
9694 // If the name is a function template, template argument deduction is
9695 // done (14.8.2.2), and if the argument deduction succeeds, the
9696 // resulting template argument list is used to generate a single
9697 // function template specialization, which is added to the set of
9698 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00009699 FunctionDecl *Specialization = 0;
Larisse Voufo43847122013-07-19 23:00:19 +00009700 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor4b52e252009-12-21 23:17:24 +00009701 if (TemplateDeductionResult Result
9702 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor092140a2013-04-17 08:45:07 +00009703 Specialization, Info,
9704 /*InOverloadResolution=*/true)) {
Larisse Voufo43847122013-07-19 23:00:19 +00009705 // Make a note of the failed deduction for diagnostics.
9706 // TODO: Actually use the failed-deduction info?
9707 FailedCandidates.addCandidate()
9708 .set(FunctionTemplate->getTemplatedDecl(),
9709 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor4b52e252009-12-21 23:17:24 +00009710 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009711 }
9712
John McCall864c0412011-04-26 20:42:42 +00009713 assert(Specialization && "no specialization and no error?");
9714
Douglas Gregor4b52e252009-12-21 23:17:24 +00009715 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009716 if (Matched) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009717 if (Complain) {
John McCall864c0412011-04-26 20:42:42 +00009718 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9719 << ovl->getName();
9720 NoteAllOverloadCandidates(ovl);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009721 }
Douglas Gregor4b52e252009-12-21 23:17:24 +00009722 return 0;
John McCall864c0412011-04-26 20:42:42 +00009723 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009724
John McCall864c0412011-04-26 20:42:42 +00009725 Matched = Specialization;
9726 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor4b52e252009-12-21 23:17:24 +00009727 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009728
Richard Smith60e141e2013-05-04 07:00:32 +00009729 if (Matched && getLangOpts().CPlusPlus1y &&
9730 Matched->getResultType()->isUndeducedType() &&
9731 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
9732 return 0;
9733
Douglas Gregor4b52e252009-12-21 23:17:24 +00009734 return Matched;
9735}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009736
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009737
9738
9739
John McCall6dbba4f2011-10-11 23:14:30 +00009740// Resolve and fix an overloaded expression that can be resolved
9741// because it identifies a single function template specialization.
9742//
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009743// Last three arguments should only be supplied if Complain = true
John McCall6dbba4f2011-10-11 23:14:30 +00009744//
9745// Return true if it was logically possible to so resolve the
9746// expression, regardless of whether or not it succeeded. Always
9747// returns true if 'complain' is set.
9748bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9749 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9750 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009751 QualType DestTypeForComplaining,
John McCall864c0412011-04-26 20:42:42 +00009752 unsigned DiagIDForComplaining) {
John McCall6dbba4f2011-10-11 23:14:30 +00009753 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009754
John McCall6dbba4f2011-10-11 23:14:30 +00009755 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009756
John McCall864c0412011-04-26 20:42:42 +00009757 DeclAccessPair found;
9758 ExprResult SingleFunctionExpression;
9759 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9760 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009761 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall6dbba4f2011-10-11 23:14:30 +00009762 SrcExpr = ExprError();
9763 return true;
9764 }
John McCall864c0412011-04-26 20:42:42 +00009765
9766 // It is only correct to resolve to an instance method if we're
9767 // resolving a form that's permitted to be a pointer to member.
9768 // Otherwise we'll end up making a bound member expression, which
9769 // is illegal in all the contexts we resolve like this.
9770 if (!ovl.HasFormOfMemberPointer &&
9771 isa<CXXMethodDecl>(fn) &&
9772 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall6dbba4f2011-10-11 23:14:30 +00009773 if (!complain) return false;
9774
9775 Diag(ovl.Expression->getExprLoc(),
9776 diag::err_bound_member_function)
9777 << 0 << ovl.Expression->getSourceRange();
9778
9779 // TODO: I believe we only end up here if there's a mix of
9780 // static and non-static candidates (otherwise the expression
9781 // would have 'bound member' type, not 'overload' type).
9782 // Ideally we would note which candidate was chosen and why
9783 // the static candidates were rejected.
9784 SrcExpr = ExprError();
9785 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009786 }
Douglas Gregordb2eae62011-03-16 19:16:25 +00009787
Sylvestre Ledru43e3dee2012-07-31 06:56:50 +00009788 // Fix the expression to refer to 'fn'.
John McCall864c0412011-04-26 20:42:42 +00009789 SingleFunctionExpression =
John McCall6dbba4f2011-10-11 23:14:30 +00009790 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall864c0412011-04-26 20:42:42 +00009791
9792 // If desired, do function-to-pointer decay.
John McCall6dbba4f2011-10-11 23:14:30 +00009793 if (doFunctionPointerConverion) {
John McCall864c0412011-04-26 20:42:42 +00009794 SingleFunctionExpression =
9795 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall6dbba4f2011-10-11 23:14:30 +00009796 if (SingleFunctionExpression.isInvalid()) {
9797 SrcExpr = ExprError();
9798 return true;
9799 }
9800 }
John McCall864c0412011-04-26 20:42:42 +00009801 }
9802
9803 if (!SingleFunctionExpression.isUsable()) {
9804 if (complain) {
9805 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9806 << ovl.Expression->getName()
9807 << DestTypeForComplaining
9808 << OpRangeForComplaining
9809 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall6dbba4f2011-10-11 23:14:30 +00009810 NoteAllOverloadCandidates(SrcExpr.get());
9811
9812 SrcExpr = ExprError();
9813 return true;
9814 }
9815
9816 return false;
John McCall864c0412011-04-26 20:42:42 +00009817 }
9818
John McCall6dbba4f2011-10-11 23:14:30 +00009819 SrcExpr = SingleFunctionExpression;
9820 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009821}
9822
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009823/// \brief Add a single candidate to the overload set.
9824static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00009825 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00009826 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009827 ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009828 OverloadCandidateSet &CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00009829 bool PartialOverloading,
9830 bool KnownValid) {
John McCall9aa472c2010-03-19 07:35:19 +00009831 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00009832 if (isa<UsingShadowDecl>(Callee))
9833 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9834
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009835 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith2ced0442011-06-26 22:19:54 +00009836 if (ExplicitTemplateArgs) {
9837 assert(!KnownValid && "Explicit template arguments?");
9838 return;
9839 }
Ahmed Charles13a140c2012-02-25 11:00:22 +00009840 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9841 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009842 return;
John McCallba135432009-11-21 08:51:07 +00009843 }
9844
9845 if (FunctionTemplateDecl *FuncTemplate
9846 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00009847 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009848 ExplicitTemplateArgs, Args, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00009849 return;
9850 }
9851
Richard Smith2ced0442011-06-26 22:19:54 +00009852 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009853}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009854
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009855/// \brief Add the overload candidates named by callee and/or found by argument
9856/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00009857void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009858 ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009859 OverloadCandidateSet &CandidateSet,
9860 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00009861
9862#ifndef NDEBUG
9863 // Verify that ArgumentDependentLookup is consistent with the rules
9864 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009865 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009866 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9867 // and let Y be the lookup set produced by argument dependent
9868 // lookup (defined as follows). If X contains
9869 //
9870 // -- a declaration of a class member, or
9871 //
9872 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00009873 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009874 //
9875 // -- a declaration that is neither a function or a function
9876 // template
9877 //
9878 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00009879
John McCall3b4294e2009-12-16 12:17:52 +00009880 if (ULE->requiresADL()) {
9881 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9882 E = ULE->decls_end(); I != E; ++I) {
9883 assert(!(*I)->getDeclContext()->isRecord());
9884 assert(isa<UsingShadowDecl>(*I) ||
9885 !(*I)->getDeclContext()->isFunctionOrMethod());
9886 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00009887 }
9888 }
9889#endif
9890
John McCall3b4294e2009-12-16 12:17:52 +00009891 // It would be nice to avoid this copy.
9892 TemplateArgumentListInfo TABuffer;
Douglas Gregor67714232011-03-03 02:41:12 +00009893 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009894 if (ULE->hasExplicitTemplateArgs()) {
9895 ULE->copyTemplateArgumentsInto(TABuffer);
9896 ExplicitTemplateArgs = &TABuffer;
9897 }
9898
9899 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9900 E = ULE->decls_end(); I != E; ++I)
Ahmed Charles13a140c2012-02-25 11:00:22 +00009901 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9902 CandidateSet, PartialOverloading,
9903 /*KnownValid*/ true);
John McCallba135432009-11-21 08:51:07 +00009904
John McCall3b4294e2009-12-16 12:17:52 +00009905 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00009906 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00009907 ULE->getExprLoc(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009908 Args, ExplicitTemplateArgs,
Richard Smithb1502bc2012-10-18 17:56:02 +00009909 CandidateSet, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009910}
John McCall578b69b2009-12-16 08:11:27 +00009911
Richard Smithd3ff3252013-06-12 22:56:54 +00009912/// Determine whether a declaration with the specified name could be moved into
9913/// a different namespace.
9914static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
9915 switch (Name.getCXXOverloadedOperator()) {
9916 case OO_New: case OO_Array_New:
9917 case OO_Delete: case OO_Array_Delete:
9918 return false;
9919
9920 default:
9921 return true;
9922 }
9923}
9924
Richard Smithf50e88a2011-06-05 22:42:48 +00009925/// Attempt to recover from an ill-formed use of a non-dependent name in a
9926/// template, where the non-dependent name was declared after the template
9927/// was defined. This is common in code written for a compilers which do not
9928/// correctly implement two-stage name lookup.
9929///
9930/// Returns true if a viable candidate was found and a diagnostic was issued.
9931static bool
9932DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9933 const CXXScopeSpec &SS, LookupResult &R,
9934 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009935 ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009936 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9937 return false;
9938
9939 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewycky5a7120c2012-03-14 20:41:00 +00009940 if (DC->isTransparentContext())
9941 continue;
9942
Richard Smithf50e88a2011-06-05 22:42:48 +00009943 SemaRef.LookupQualifiedName(R, DC);
9944
9945 if (!R.empty()) {
9946 R.suppressDiagnostics();
9947
9948 if (isa<CXXRecordDecl>(DC)) {
9949 // Don't diagnose names we find in classes; we get much better
9950 // diagnostics for these from DiagnoseEmptyLookup.
9951 R.clear();
9952 return false;
9953 }
9954
9955 OverloadCandidateSet Candidates(FnLoc);
9956 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9957 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009958 ExplicitTemplateArgs, Args,
Richard Smith2ced0442011-06-26 22:19:54 +00009959 Candidates, false, /*KnownValid*/ false);
Richard Smithf50e88a2011-06-05 22:42:48 +00009960
9961 OverloadCandidateSet::iterator Best;
Richard Smith2ced0442011-06-26 22:19:54 +00009962 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009963 // No viable functions. Don't bother the user with notes for functions
9964 // which don't work and shouldn't be found anyway.
Richard Smith2ced0442011-06-26 22:19:54 +00009965 R.clear();
Richard Smithf50e88a2011-06-05 22:42:48 +00009966 return false;
Richard Smith2ced0442011-06-26 22:19:54 +00009967 }
Richard Smithf50e88a2011-06-05 22:42:48 +00009968
9969 // Find the namespaces where ADL would have looked, and suggest
9970 // declaring the function there instead.
9971 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9972 Sema::AssociatedClassSet AssociatedClasses;
John McCall42f48fb2012-08-24 20:38:34 +00009973 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009974 AssociatedNamespaces,
9975 AssociatedClasses);
Chandler Carruth74d487e2011-06-05 23:36:55 +00009976 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smithd3ff3252013-06-12 22:56:54 +00009977 if (canBeDeclaredInNamespace(R.getLookupName())) {
9978 DeclContext *Std = SemaRef.getStdNamespace();
9979 for (Sema::AssociatedNamespaceSet::iterator
9980 it = AssociatedNamespaces.begin(),
9981 end = AssociatedNamespaces.end(); it != end; ++it) {
9982 // Never suggest declaring a function within namespace 'std'.
9983 if (Std && Std->Encloses(*it))
9984 continue;
Richard Smith19e0d952012-12-22 02:46:14 +00009985
Richard Smithd3ff3252013-06-12 22:56:54 +00009986 // Never suggest declaring a function within a namespace with a
9987 // reserved name, like __gnu_cxx.
9988 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
9989 if (NS &&
9990 NS->getQualifiedNameAsString().find("__") != std::string::npos)
9991 continue;
9992
9993 SuggestedNamespaces.insert(*it);
9994 }
Richard Smithf50e88a2011-06-05 22:42:48 +00009995 }
9996
9997 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9998 << R.getLookupName();
Chandler Carruth74d487e2011-06-05 23:36:55 +00009999 if (SuggestedNamespaces.empty()) {
Richard Smithf50e88a2011-06-05 22:42:48 +000010000 SemaRef.Diag(Best->Function->getLocation(),
10001 diag::note_not_found_by_two_phase_lookup)
10002 << R.getLookupName() << 0;
Chandler Carruth74d487e2011-06-05 23:36:55 +000010003 } else if (SuggestedNamespaces.size() == 1) {
Richard Smithf50e88a2011-06-05 22:42:48 +000010004 SemaRef.Diag(Best->Function->getLocation(),
10005 diag::note_not_found_by_two_phase_lookup)
Chandler Carruth74d487e2011-06-05 23:36:55 +000010006 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smithf50e88a2011-06-05 22:42:48 +000010007 } else {
10008 // FIXME: It would be useful to list the associated namespaces here,
10009 // but the diagnostics infrastructure doesn't provide a way to produce
10010 // a localized representation of a list of items.
10011 SemaRef.Diag(Best->Function->getLocation(),
10012 diag::note_not_found_by_two_phase_lookup)
10013 << R.getLookupName() << 2;
10014 }
10015
10016 // Try to recover by calling this function.
10017 return true;
10018 }
10019
10020 R.clear();
10021 }
10022
10023 return false;
10024}
10025
10026/// Attempt to recover from ill-formed use of a non-dependent operator in a
10027/// template, where the non-dependent operator was declared after the template
10028/// was defined.
10029///
10030/// Returns true if a viable candidate was found and a diagnostic was issued.
10031static bool
10032DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10033 SourceLocation OpLoc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010034 ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +000010035 DeclarationName OpName =
10036 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10037 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10038 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010039 /*ExplicitTemplateArgs=*/0, Args);
Richard Smithf50e88a2011-06-05 22:42:48 +000010040}
10041
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +000010042namespace {
Richard Smithe49ff3e2012-09-25 04:46:05 +000010043class BuildRecoveryCallExprRAII {
10044 Sema &SemaRef;
10045public:
10046 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10047 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10048 SemaRef.IsBuildingRecoveryCallExpr = true;
10049 }
10050
10051 ~BuildRecoveryCallExprRAII() {
10052 SemaRef.IsBuildingRecoveryCallExpr = false;
10053 }
10054};
10055
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +000010056}
10057
John McCall578b69b2009-12-16 08:11:27 +000010058/// Attempts to recover from a call where no functions were found.
10059///
10060/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +000010061static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +000010062BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +000010063 UnresolvedLookupExpr *ULE,
10064 SourceLocation LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010065 llvm::MutableArrayRef<Expr *> Args,
Richard Smithf50e88a2011-06-05 22:42:48 +000010066 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +000010067 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smithe49ff3e2012-09-25 04:46:05 +000010068 // Do not try to recover if it is already building a recovery call.
10069 // This stops infinite loops for template instantiations like
10070 //
10071 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10072 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10073 //
10074 if (SemaRef.IsBuildingRecoveryCallExpr)
10075 return ExprError();
10076 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCall578b69b2009-12-16 08:11:27 +000010077
10078 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +000010079 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnarae4b92762012-01-27 09:46:47 +000010080 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCall578b69b2009-12-16 08:11:27 +000010081
John McCall3b4294e2009-12-16 12:17:52 +000010082 TemplateArgumentListInfo TABuffer;
Richard Smithf50e88a2011-06-05 22:42:48 +000010083 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +000010084 if (ULE->hasExplicitTemplateArgs()) {
10085 ULE->copyTemplateArgumentsInto(TABuffer);
10086 ExplicitTemplateArgs = &TABuffer;
10087 }
10088
John McCall578b69b2009-12-16 08:11:27 +000010089 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10090 Sema::LookupOrdinaryName);
Kaelyn Uhrain761695f2013-07-08 23:13:39 +000010091 FunctionCallFilterCCC Validator(SemaRef, Args.size(),
10092 ExplicitTemplateArgs != 0);
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +000010093 NoTypoCorrectionCCC RejectAll;
10094 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
10095 (CorrectionCandidateCallback*)&Validator :
10096 (CorrectionCandidateCallback*)&RejectAll;
Richard Smithf50e88a2011-06-05 22:42:48 +000010097 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010098 ExplicitTemplateArgs, Args) &&
Richard Smithf50e88a2011-06-05 22:42:48 +000010099 (!EmptyLookup ||
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +000010100 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010101 ExplicitTemplateArgs, Args)))
John McCallf312b1e2010-08-26 23:41:50 +000010102 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +000010103
John McCall3b4294e2009-12-16 12:17:52 +000010104 assert(!R.empty() && "lookup results empty despite recovery");
10105
10106 // Build an implicit member call if appropriate. Just drop the
10107 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +000010108 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +000010109 if ((*R.begin())->isCXXClassMember())
Abramo Bagnarae4b92762012-01-27 09:46:47 +000010110 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
10111 R, ExplicitTemplateArgs);
Abramo Bagnara9d9922a2012-02-06 14:31:00 +000010112 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnarae4b92762012-01-27 09:46:47 +000010113 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara9d9922a2012-02-06 14:31:00 +000010114 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +000010115 else
10116 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10117
10118 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +000010119 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +000010120
10121 // This shouldn't cause an infinite loop because we're giving it
Richard Smithf50e88a2011-06-05 22:42:48 +000010122 // an expression with viable lookup results, which should never
John McCall3b4294e2009-12-16 12:17:52 +000010123 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +000010124 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010125 MultiExprArg(Args.data(), Args.size()),
10126 RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +000010127}
Douglas Gregord7a95972010-06-08 17:35:15 +000010128
Sam Panzere1715b62012-08-21 00:52:01 +000010129/// \brief Constructs and populates an OverloadedCandidateSet from
10130/// the given function.
10131/// \returns true when an the ExprResult output parameter has been set.
10132bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10133 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010134 MultiExprArg Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010135 SourceLocation RParenLoc,
10136 OverloadCandidateSet *CandidateSet,
10137 ExprResult *Result) {
John McCall3b4294e2009-12-16 12:17:52 +000010138#ifndef NDEBUG
10139 if (ULE->requiresADL()) {
10140 // To do ADL, we must have found an unqualified name.
10141 assert(!ULE->getQualifier() && "qualified name with ADL");
10142
10143 // We don't perform ADL for implicit declarations of builtins.
10144 // Verify that this was correctly set up.
10145 FunctionDecl *F;
10146 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10147 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10148 F->getBuiltinID() && F->isImplicit())
David Blaikieb219cfc2011-09-23 05:06:16 +000010149 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010150
John McCall3b4294e2009-12-16 12:17:52 +000010151 // We don't perform ADL in C.
David Blaikie4e4d0842012-03-11 07:00:24 +000010152 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb1502bc2012-10-18 17:56:02 +000010153 }
John McCall3b4294e2009-12-16 12:17:52 +000010154#endif
10155
John McCall5acb0c92011-10-17 18:40:02 +000010156 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010157 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzere1715b62012-08-21 00:52:01 +000010158 *Result = ExprError();
10159 return true;
10160 }
Douglas Gregor17330012009-02-04 15:01:18 +000010161
John McCall3b4294e2009-12-16 12:17:52 +000010162 // Add the functions denoted by the callee to the set of candidate
10163 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010164 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +000010165
10166 // If we found nothing, try to recover.
Richard Smithf50e88a2011-06-05 22:42:48 +000010167 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
10168 // out if it fails.
Sam Panzere1715b62012-08-21 00:52:01 +000010169 if (CandidateSet->empty()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +000010170 // In Microsoft mode, if we are inside a template class member function then
10171 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichet0f74d1e2011-09-07 00:14:57 +000010172 // to instantiation time to be able to search into type dependent base
Sebastian Redl14b0c192011-09-24 17:48:00 +000010173 // classes.
David Blaikie4e4d0842012-03-11 07:00:24 +000010174 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetc8ff9152011-11-25 01:10:54 +000010175 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010176 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010177 Context.DependentTy, VK_RValue,
10178 RParenLoc);
Sebastian Redl14b0c192011-09-24 17:48:00 +000010179 CE->setTypeDependent(true);
Sam Panzere1715b62012-08-21 00:52:01 +000010180 *Result = Owned(CE);
10181 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +000010182 }
Sam Panzere1715b62012-08-21 00:52:01 +000010183 return false;
Francois Pichet0f74d1e2011-09-07 00:14:57 +000010184 }
John McCall578b69b2009-12-16 08:11:27 +000010185
John McCall5acb0c92011-10-17 18:40:02 +000010186 UnbridgedCasts.restore();
Sam Panzere1715b62012-08-21 00:52:01 +000010187 return false;
10188}
John McCall5acb0c92011-10-17 18:40:02 +000010189
Sam Panzere1715b62012-08-21 00:52:01 +000010190/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10191/// the completed call expression. If overload resolution fails, emits
10192/// diagnostics and returns ExprError()
10193static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10194 UnresolvedLookupExpr *ULE,
10195 SourceLocation LParenLoc,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010196 MultiExprArg Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010197 SourceLocation RParenLoc,
10198 Expr *ExecConfig,
10199 OverloadCandidateSet *CandidateSet,
10200 OverloadCandidateSet::iterator *Best,
10201 OverloadingResult OverloadResult,
10202 bool AllowTypoCorrection) {
10203 if (CandidateSet->empty())
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010204 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010205 RParenLoc, /*EmptyLookup=*/true,
10206 AllowTypoCorrection);
10207
10208 switch (OverloadResult) {
John McCall3b4294e2009-12-16 12:17:52 +000010209 case OR_Success: {
Sam Panzere1715b62012-08-21 00:52:01 +000010210 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzere1715b62012-08-21 00:52:01 +000010211 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +000010212 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10213 return ExprError();
Sam Panzere1715b62012-08-21 00:52:01 +000010214 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010215 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10216 ExecConfig);
John McCall3b4294e2009-12-16 12:17:52 +000010217 }
Douglas Gregorf6b89692008-11-26 05:54:23 +000010218
Richard Smithf50e88a2011-06-05 22:42:48 +000010219 case OR_No_Viable_Function: {
10220 // Try to recover by looking for viable functions which the user might
10221 // have meant to call.
Sam Panzere1715b62012-08-21 00:52:01 +000010222 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010223 Args, RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +000010224 /*EmptyLookup=*/false,
10225 AllowTypoCorrection);
Richard Smithf50e88a2011-06-05 22:42:48 +000010226 if (!Recovery.isInvalid())
10227 return Recovery;
10228
Sam Panzere1715b62012-08-21 00:52:01 +000010229 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregorf6b89692008-11-26 05:54:23 +000010230 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +000010231 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010232 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregorf6b89692008-11-26 05:54:23 +000010233 break;
Richard Smithf50e88a2011-06-05 22:42:48 +000010234 }
Douglas Gregorf6b89692008-11-26 05:54:23 +000010235
10236 case OR_Ambiguous:
Sam Panzere1715b62012-08-21 00:52:01 +000010237 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +000010238 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010239 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregorf6b89692008-11-26 05:54:23 +000010240 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010241
Sam Panzere1715b62012-08-21 00:52:01 +000010242 case OR_Deleted: {
10243 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10244 << (*Best)->Function->isDeleted()
10245 << ULE->getName()
10246 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10247 << Fn->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010248 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis0d579b62011-11-04 15:58:13 +000010249
Sam Panzere1715b62012-08-21 00:52:01 +000010250 // We emitted an error for the unvailable/deleted function call but keep
10251 // the call in the AST.
10252 FunctionDecl *FDecl = (*Best)->Function;
10253 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010254 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10255 ExecConfig);
Sam Panzere1715b62012-08-21 00:52:01 +000010256 }
Douglas Gregorf6b89692008-11-26 05:54:23 +000010257 }
10258
Douglas Gregorff331c12010-07-25 18:17:45 +000010259 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +000010260 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +000010261}
10262
Sam Panzere1715b62012-08-21 00:52:01 +000010263/// BuildOverloadedCallExpr - Given the call expression that calls Fn
10264/// (which eventually refers to the declaration Func) and the call
10265/// arguments Args/NumArgs, attempt to resolve the function call down
10266/// to a specific function. If overload resolution succeeds, returns
10267/// the call expression produced by overload resolution.
10268/// Otherwise, emits diagnostics and returns ExprError.
10269ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10270 UnresolvedLookupExpr *ULE,
10271 SourceLocation LParenLoc,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010272 MultiExprArg Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010273 SourceLocation RParenLoc,
10274 Expr *ExecConfig,
10275 bool AllowTypoCorrection) {
10276 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
10277 ExprResult result;
10278
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010279 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10280 &result))
Sam Panzere1715b62012-08-21 00:52:01 +000010281 return result;
10282
10283 OverloadCandidateSet::iterator Best;
10284 OverloadingResult OverloadResult =
10285 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10286
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010287 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010288 RParenLoc, ExecConfig, &CandidateSet,
10289 &Best, OverloadResult,
10290 AllowTypoCorrection);
10291}
10292
John McCall6e266892010-01-26 03:27:55 +000010293static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +000010294 return Functions.size() > 1 ||
10295 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10296}
10297
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010298/// \brief Create a unary operation that may resolve to an overloaded
10299/// operator.
10300///
10301/// \param OpLoc The location of the operator itself (e.g., '*').
10302///
10303/// \param OpcIn The UnaryOperator::Opcode that describes this
10304/// operator.
10305///
James Dennett40ae6662012-06-22 08:52:37 +000010306/// \param Fns The set of non-member functions that will be
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010307/// considered by overload resolution. The caller needs to build this
10308/// set based on the context using, e.g.,
10309/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10310/// set should not contain any member functions; those will be added
10311/// by CreateOverloadedUnaryOp().
10312///
James Dennett8da16872012-06-22 10:32:46 +000010313/// \param Input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010314ExprResult
John McCall6e266892010-01-26 03:27:55 +000010315Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10316 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +000010317 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010318 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010319
10320 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10321 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10322 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +000010323 // TODO: provide better source location info.
10324 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010325
John McCall5acb0c92011-10-17 18:40:02 +000010326 if (checkPlaceholderForOverload(*this, Input))
10327 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010328
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010329 Expr *Args[2] = { Input, 0 };
10330 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +000010331
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010332 // For post-increment and post-decrement, add the implicit '0' as
10333 // the second argument, so that we know this is a post-increment or
10334 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +000010335 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010336 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +000010337 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10338 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010339 NumArgs = 2;
10340 }
10341
Richard Smith958ba642013-05-05 15:51:06 +000010342 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10343
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010344 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010345 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +000010346 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010347 Opc,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010348 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010349 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010350 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010351
John McCallc373d482010-01-27 01:50:18 +000010352 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +000010353 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010354 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010355 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010356 /*ADL*/ true, IsOverloaded(Fns),
10357 Fns.begin(), Fns.end());
Richard Smith958ba642013-05-05 15:51:06 +000010358 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, ArgsArray,
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010359 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010360 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +000010361 OpLoc, false));
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010362 }
10363
10364 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010365 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010366
10367 // Add the candidates from the given function set.
Richard Smith958ba642013-05-05 15:51:06 +000010368 AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010369
10370 // Add operator candidates that are member functions.
Richard Smith958ba642013-05-05 15:51:06 +000010371 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010372
John McCall6e266892010-01-26 03:27:55 +000010373 // Add candidates from ADL.
Richard Smith958ba642013-05-05 15:51:06 +000010374 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, OpLoc,
10375 ArgsArray, /*ExplicitTemplateArgs*/ 0,
John McCall6e266892010-01-26 03:27:55 +000010376 CandidateSet);
10377
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010378 // Add builtin operator candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010379 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010380
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010381 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10382
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010383 // Perform overload resolution.
10384 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010385 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010386 case OR_Success: {
10387 // We found a built-in operator or an overloaded operator.
10388 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +000010389
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010390 if (FnDecl) {
10391 // We matched an overloaded operator. Build a call to that
10392 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +000010393
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010394 // Convert the arguments.
10395 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +000010396 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010397
John Wiegley429bb272011-04-08 18:41:53 +000010398 ExprResult InputRes =
10399 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10400 Best->FoundDecl, Method);
10401 if (InputRes.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010402 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010403 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010404 } else {
10405 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010406 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +000010407 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010408 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +000010409 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010410 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +000010411 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +000010412 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010413 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +000010414 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010415 }
10416
John McCallf89e55a2010-11-18 06:31:45 +000010417 // Determine the result type.
10418 QualType ResultTy = FnDecl->getResultType();
10419 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10420 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +000010421
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010422 // Build the actual expression node.
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010423 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010424 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010425 if (FnExpr.isInvalid())
10426 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +000010427
Eli Friedman4c3b8962009-11-18 03:58:17 +000010428 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +000010429 CallExpr *TheCall =
Richard Smith958ba642013-05-05 15:51:06 +000010430 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), ArgsArray,
Lang Hamesbe9af122012-10-02 04:45:10 +000010431 ResultTy, VK, OpLoc, false);
John McCallb697e082010-05-06 18:15:07 +000010432
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010433 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +000010434 FnDecl))
10435 return ExprError();
10436
John McCall9ae2f072010-08-23 23:25:46 +000010437 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010438 } else {
10439 // We matched a built-in operator. Convert the arguments, then
10440 // break out so that we will build the appropriate built-in
10441 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010442 ExprResult InputRes =
10443 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10444 Best->Conversions[0], AA_Passing);
10445 if (InputRes.isInvalid())
10446 return ExprError();
10447 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010448 break;
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010449 }
John Wiegley429bb272011-04-08 18:41:53 +000010450 }
10451
10452 case OR_No_Viable_Function:
Richard Smithf50e88a2011-06-05 22:42:48 +000010453 // This is an erroneous use of an operator which can be overloaded by
10454 // a non-member function. Check for non-member operators which were
10455 // defined too late to be candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010456 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smithf50e88a2011-06-05 22:42:48 +000010457 // FIXME: Recover by calling the found function.
10458 return ExprError();
10459
John Wiegley429bb272011-04-08 18:41:53 +000010460 // No viable function; fall through to handling this as a
10461 // built-in operator, which will produce an error message for us.
10462 break;
10463
10464 case OR_Ambiguous:
10465 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10466 << UnaryOperator::getOpcodeStr(Opc)
10467 << Input->getType()
10468 << Input->getSourceRange();
Richard Smith958ba642013-05-05 15:51:06 +000010469 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley429bb272011-04-08 18:41:53 +000010470 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10471 return ExprError();
10472
10473 case OR_Deleted:
10474 Diag(OpLoc, diag::err_ovl_deleted_oper)
10475 << Best->Function->isDeleted()
10476 << UnaryOperator::getOpcodeStr(Opc)
10477 << getDeletedOrUnavailableSuffix(Best->Function)
10478 << Input->getSourceRange();
Richard Smith958ba642013-05-05 15:51:06 +000010479 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman1795d372011-08-26 19:46:22 +000010480 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010481 return ExprError();
10482 }
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010483
10484 // Either we found no viable overloaded operator or we matched a
10485 // built-in operator. In either case, fall through to trying to
10486 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +000010487 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010488}
10489
Douglas Gregor063daf62009-03-13 18:40:31 +000010490/// \brief Create a binary operation that may resolve to an overloaded
10491/// operator.
10492///
10493/// \param OpLoc The location of the operator itself (e.g., '+').
10494///
10495/// \param OpcIn The BinaryOperator::Opcode that describes this
10496/// operator.
10497///
James Dennett40ae6662012-06-22 08:52:37 +000010498/// \param Fns The set of non-member functions that will be
Douglas Gregor063daf62009-03-13 18:40:31 +000010499/// considered by overload resolution. The caller needs to build this
10500/// set based on the context using, e.g.,
10501/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10502/// set should not contain any member functions; those will be added
10503/// by CreateOverloadedBinOp().
10504///
10505/// \param LHS Left-hand argument.
10506/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010507ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +000010508Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +000010509 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +000010510 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +000010511 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +000010512 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010513 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +000010514
10515 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10516 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10517 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10518
10519 // If either side is type-dependent, create an appropriate dependent
10520 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010521 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +000010522 if (Fns.empty()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010523 // If there are no functions to store, just build a dependent
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010524 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +000010525 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010526 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +000010527 Context.DependentTy,
10528 VK_RValue, OK_Ordinary,
Lang Hamesbe9af122012-10-02 04:45:10 +000010529 OpLoc,
10530 FPFeatures.fp_contract));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010531
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010532 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10533 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010534 VK_LValue,
10535 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010536 Context.DependentTy,
10537 Context.DependentTy,
Lang Hamesbe9af122012-10-02 04:45:10 +000010538 OpLoc,
10539 FPFeatures.fp_contract));
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010540 }
John McCall6e266892010-01-26 03:27:55 +000010541
10542 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +000010543 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010544 // TODO: provide better source location info in DNLoc component.
10545 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +000010546 UnresolvedLookupExpr *Fn
Douglas Gregor4c9be892011-02-28 20:01:57 +000010547 = UnresolvedLookupExpr::Create(Context, NamingClass,
10548 NestedNameSpecifierLoc(), OpNameInfo,
10549 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010550 Fns.begin(), Fns.end());
Lang Hamesbe9af122012-10-02 04:45:10 +000010551 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10552 Context.DependentTy, VK_RValue,
10553 OpLoc, FPFeatures.fp_contract));
Douglas Gregor063daf62009-03-13 18:40:31 +000010554 }
10555
John McCall5acb0c92011-10-17 18:40:02 +000010556 // Always do placeholder-like conversions on the RHS.
10557 if (checkPlaceholderForOverload(*this, Args[1]))
10558 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010559
John McCall3c3b7f92011-10-25 17:37:35 +000010560 // Do placeholder-like conversion on the LHS; note that we should
10561 // not get here with a PseudoObject LHS.
10562 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall5acb0c92011-10-17 18:40:02 +000010563 if (checkPlaceholderForOverload(*this, Args[0]))
10564 return ExprError();
10565
Sebastian Redl275c2b42009-11-18 23:10:33 +000010566 // If this is the assignment operator, we only perform overload resolution
10567 // if the left-hand side is a class or enumeration type. This is actually
10568 // a hack. The standard requires that we do overload resolution between the
10569 // various built-in candidates, but as DR507 points out, this can lead to
10570 // problems. So we do it this way, which pretty much follows what GCC does.
10571 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +000010572 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010573 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010574
John McCall0e800c92010-12-04 08:14:53 +000010575 // If this is the .* operator, which is not overloadable, just
10576 // create a built-in binary operator.
10577 if (Opc == BO_PtrMemD)
10578 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10579
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010580 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010581 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010582
10583 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010584 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +000010585
10586 // Add operator candidates that are member functions.
Richard Smith958ba642013-05-05 15:51:06 +000010587 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +000010588
John McCall6e266892010-01-26 03:27:55 +000010589 // Add candidates from ADL.
10590 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010591 OpLoc, Args,
John McCall6e266892010-01-26 03:27:55 +000010592 /*ExplicitTemplateArgs*/ 0,
10593 CandidateSet);
10594
Douglas Gregor063daf62009-03-13 18:40:31 +000010595 // Add builtin operator candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010596 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +000010597
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010598 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10599
Douglas Gregor063daf62009-03-13 18:40:31 +000010600 // Perform overload resolution.
10601 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010602 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +000010603 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +000010604 // We found a built-in operator or an overloaded operator.
10605 FunctionDecl *FnDecl = Best->Function;
10606
10607 if (FnDecl) {
10608 // We matched an overloaded operator. Build a call to that
10609 // operator.
10610
10611 // Convert the arguments.
10612 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +000010613 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +000010614 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010615
Chandler Carruth6df868e2010-12-12 08:17:55 +000010616 ExprResult Arg1 =
10617 PerformCopyInitialization(
10618 InitializedEntity::InitializeParameter(Context,
10619 FnDecl->getParamDecl(0)),
10620 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010621 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010622 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010623
John Wiegley429bb272011-04-08 18:41:53 +000010624 ExprResult Arg0 =
10625 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10626 Best->FoundDecl, Method);
10627 if (Arg0.isInvalid())
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010628 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010629 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010630 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010631 } else {
10632 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +000010633 ExprResult Arg0 = PerformCopyInitialization(
10634 InitializedEntity::InitializeParameter(Context,
10635 FnDecl->getParamDecl(0)),
10636 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010637 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010638 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010639
Chandler Carruth6df868e2010-12-12 08:17:55 +000010640 ExprResult Arg1 =
10641 PerformCopyInitialization(
10642 InitializedEntity::InitializeParameter(Context,
10643 FnDecl->getParamDecl(1)),
10644 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010645 if (Arg1.isInvalid())
10646 return ExprError();
10647 Args[0] = LHS = Arg0.takeAs<Expr>();
10648 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010649 }
10650
John McCallf89e55a2010-11-18 06:31:45 +000010651 // Determine the result type.
10652 QualType ResultTy = FnDecl->getResultType();
10653 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10654 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +000010655
10656 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010657 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010658 Best->FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010659 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010660 if (FnExpr.isInvalid())
10661 return ExprError();
Douglas Gregor063daf62009-03-13 18:40:31 +000010662
John McCall9ae2f072010-08-23 23:25:46 +000010663 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010664 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000010665 Args, ResultTy, VK, OpLoc,
10666 FPFeatures.fp_contract);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010667
10668 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000010669 FnDecl))
10670 return ExprError();
10671
Nick Lewycky9b7ea0d2013-01-24 02:03:08 +000010672 ArrayRef<const Expr *> ArgsArray(Args, 2);
10673 // Cut off the implicit 'this'.
10674 if (isa<CXXMethodDecl>(FnDecl))
10675 ArgsArray = ArgsArray.slice(1);
10676 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
10677 TheCall->getSourceRange(), VariadicDoesNotApply);
10678
John McCall9ae2f072010-08-23 23:25:46 +000010679 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +000010680 } else {
10681 // We matched a built-in operator. Convert the arguments, then
10682 // break out so that we will build the appropriate built-in
10683 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010684 ExprResult ArgsRes0 =
10685 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10686 Best->Conversions[0], AA_Passing);
10687 if (ArgsRes0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010688 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010689 Args[0] = ArgsRes0.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010690
John Wiegley429bb272011-04-08 18:41:53 +000010691 ExprResult ArgsRes1 =
10692 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10693 Best->Conversions[1], AA_Passing);
10694 if (ArgsRes1.isInvalid())
10695 return ExprError();
10696 Args[1] = ArgsRes1.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010697 break;
10698 }
10699 }
10700
Douglas Gregor33074752009-09-30 21:46:01 +000010701 case OR_No_Viable_Function: {
10702 // C++ [over.match.oper]p9:
10703 // If the operator is the operator , [...] and there are no
10704 // viable functions, then the operator is assumed to be the
10705 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +000010706 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +000010707 break;
10708
Chandler Carruth6df868e2010-12-12 08:17:55 +000010709 // For class as left operand for assignment or compound assigment
10710 // operator do not fall through to handling in built-in, but report that
10711 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +000010712 ExprResult Result = ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010713 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +000010714 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +000010715 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10716 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010717 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedman3f93d4c2013-08-28 20:35:35 +000010718 if (Args[0]->getType()->isIncompleteType()) {
10719 Diag(OpLoc, diag::note_assign_lhs_incomplete)
10720 << Args[0]->getType()
10721 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10722 }
Douglas Gregor33074752009-09-30 21:46:01 +000010723 } else {
Richard Smithf50e88a2011-06-05 22:42:48 +000010724 // This is an erroneous use of an operator which can be overloaded by
10725 // a non-member function. Check for non-member operators which were
10726 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010727 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smithf50e88a2011-06-05 22:42:48 +000010728 // FIXME: Recover by calling the found function.
10729 return ExprError();
10730
Douglas Gregor33074752009-09-30 21:46:01 +000010731 // No viable function; try to create a built-in operation, which will
10732 // produce an error. Then, show the non-viable candidates.
10733 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +000010734 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010735 assert(Result.isInvalid() &&
Douglas Gregor33074752009-09-30 21:46:01 +000010736 "C++ binary operator overloading is missing candidates!");
10737 if (Result.isInvalid())
Ahmed Charles13a140c2012-02-25 11:00:22 +000010738 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010739 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010740 return Result;
Douglas Gregor33074752009-09-30 21:46:01 +000010741 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010742
10743 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010744 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +000010745 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +000010746 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010747 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010748 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010749 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010750 return ExprError();
10751
10752 case OR_Deleted:
Douglas Gregore4e68d42012-02-15 19:33:52 +000010753 if (isImplicitlyDeleted(Best->Function)) {
10754 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10755 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smith0f46e642012-12-28 12:23:24 +000010756 << Context.getRecordType(Method->getParent())
10757 << getSpecialMember(Method);
Richard Smith5bdaac52012-04-02 20:59:25 +000010758
Richard Smith0f46e642012-12-28 12:23:24 +000010759 // The user probably meant to call this special member. Just
10760 // explain why it's deleted.
10761 NoteDeletedFunction(Method);
10762 return ExprError();
Douglas Gregore4e68d42012-02-15 19:33:52 +000010763 } else {
10764 Diag(OpLoc, diag::err_ovl_deleted_oper)
10765 << Best->Function->isDeleted()
10766 << BinaryOperator::getOpcodeStr(Opc)
10767 << getDeletedOrUnavailableSuffix(Best->Function)
10768 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10769 }
Ahmed Charles13a140c2012-02-25 11:00:22 +000010770 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman1795d372011-08-26 19:46:22 +000010771 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010772 return ExprError();
John McCall1d318332010-01-12 00:44:57 +000010773 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010774
Douglas Gregor33074752009-09-30 21:46:01 +000010775 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010776 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010777}
10778
John McCall60d7b3a2010-08-24 06:29:42 +000010779ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +000010780Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10781 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010782 Expr *Base, Expr *Idx) {
10783 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +000010784 DeclarationName OpName =
10785 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10786
10787 // If either side is type-dependent, create an appropriate dependent
10788 // expression.
10789 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10790
John McCallc373d482010-01-27 01:50:18 +000010791 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010792 // CHECKME: no 'operator' keyword?
10793 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10794 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +000010795 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010796 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010797 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010798 /*ADL*/ true, /*Overloaded*/ false,
10799 UnresolvedSetIterator(),
10800 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +000010801 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +000010802
Sebastian Redlf322ed62009-10-29 20:17:01 +000010803 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010804 Args,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010805 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010806 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +000010807 RLoc, false));
Sebastian Redlf322ed62009-10-29 20:17:01 +000010808 }
10809
John McCall5acb0c92011-10-17 18:40:02 +000010810 // Handle placeholders on both operands.
10811 if (checkPlaceholderForOverload(*this, Args[0]))
10812 return ExprError();
10813 if (checkPlaceholderForOverload(*this, Args[1]))
10814 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010815
Sebastian Redlf322ed62009-10-29 20:17:01 +000010816 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010817 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010818
10819 // Subscript can only be overloaded as a member function.
10820
10821 // Add operator candidates that are member functions.
Richard Smith958ba642013-05-05 15:51:06 +000010822 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010823
10824 // Add builtin operator candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010825 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010826
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010827 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10828
Sebastian Redlf322ed62009-10-29 20:17:01 +000010829 // Perform overload resolution.
10830 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010831 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +000010832 case OR_Success: {
10833 // We found a built-in operator or an overloaded operator.
10834 FunctionDecl *FnDecl = Best->Function;
10835
10836 if (FnDecl) {
10837 // We matched an overloaded operator. Build a call to that
10838 // operator.
10839
John McCall9aa472c2010-03-19 07:35:19 +000010840 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallc373d482010-01-27 01:50:18 +000010841
Sebastian Redlf322ed62009-10-29 20:17:01 +000010842 // Convert the arguments.
10843 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley429bb272011-04-08 18:41:53 +000010844 ExprResult Arg0 =
10845 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10846 Best->FoundDecl, Method);
10847 if (Arg0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010848 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010849 Args[0] = Arg0.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010850
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010851 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010852 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010853 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010854 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010855 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010856 SourceLocation(),
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010857 Owned(Args[1]));
10858 if (InputInit.isInvalid())
10859 return ExprError();
10860
10861 Args[1] = InputInit.takeAs<Expr>();
10862
Sebastian Redlf322ed62009-10-29 20:17:01 +000010863 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +000010864 QualType ResultTy = FnDecl->getResultType();
10865 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10866 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010867
10868 // Build the actual expression node.
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010869 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10870 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010871 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010872 Best->FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010873 HadMultipleCandidates,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010874 OpLocInfo.getLoc(),
10875 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010876 if (FnExpr.isInvalid())
10877 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010878
John McCall9ae2f072010-08-23 23:25:46 +000010879 CXXOperatorCallExpr *TheCall =
10880 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010881 FnExpr.take(), Args,
Lang Hamesbe9af122012-10-02 04:45:10 +000010882 ResultTy, VK, RLoc,
10883 false);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010884
John McCall9ae2f072010-08-23 23:25:46 +000010885 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010886 FnDecl))
10887 return ExprError();
10888
John McCall9ae2f072010-08-23 23:25:46 +000010889 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010890 } else {
10891 // We matched a built-in operator. Convert the arguments, then
10892 // break out so that we will build the appropriate built-in
10893 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010894 ExprResult ArgsRes0 =
10895 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10896 Best->Conversions[0], AA_Passing);
10897 if (ArgsRes0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010898 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010899 Args[0] = ArgsRes0.take();
10900
10901 ExprResult ArgsRes1 =
10902 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10903 Best->Conversions[1], AA_Passing);
10904 if (ArgsRes1.isInvalid())
10905 return ExprError();
10906 Args[1] = ArgsRes1.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010907
10908 break;
10909 }
10910 }
10911
10912 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +000010913 if (CandidateSet.empty())
10914 Diag(LLoc, diag::err_ovl_no_oper)
10915 << Args[0]->getType() << /*subscript*/ 0
10916 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10917 else
10918 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10919 << Args[0]->getType()
10920 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010921 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010922 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +000010923 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010924 }
10925
10926 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010927 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010928 << "[]"
Douglas Gregorae2cf762010-11-13 20:06:38 +000010929 << Args[0]->getType() << Args[1]->getType()
10930 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010931 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010932 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010933 return ExprError();
10934
10935 case OR_Deleted:
10936 Diag(LLoc, diag::err_ovl_deleted_oper)
10937 << Best->Function->isDeleted() << "[]"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010938 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redlf322ed62009-10-29 20:17:01 +000010939 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010940 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010941 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010942 return ExprError();
10943 }
10944
10945 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +000010946 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010947}
10948
Douglas Gregor88a35142008-12-22 05:46:06 +000010949/// BuildCallToMemberFunction - Build a call to a member
10950/// function. MemExpr is the expression that refers to the member
10951/// function (and includes the object parameter), Args/NumArgs are the
10952/// arguments to the function call (not including the object
10953/// parameter). The caller needs to validate that the member
John McCall864c0412011-04-26 20:42:42 +000010954/// expression refers to a non-static member function or an overloaded
10955/// member function.
John McCall60d7b3a2010-08-24 06:29:42 +000010956ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +000010957Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010958 SourceLocation LParenLoc,
10959 MultiExprArg Args,
10960 SourceLocation RParenLoc) {
John McCall864c0412011-04-26 20:42:42 +000010961 assert(MemExprE->getType() == Context.BoundMemberTy ||
10962 MemExprE->getType() == Context.OverloadTy);
10963
Douglas Gregor88a35142008-12-22 05:46:06 +000010964 // Dig out the member expression. This holds both the object
10965 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +000010966 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010967
John McCall864c0412011-04-26 20:42:42 +000010968 // Determine whether this is a call to a pointer-to-member function.
10969 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10970 assert(op->getType() == Context.BoundMemberTy);
10971 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10972
10973 QualType fnType =
10974 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10975
10976 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10977 QualType resultType = proto->getCallResultType(Context);
10978 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10979
10980 // Check that the object type isn't more qualified than the
10981 // member function we're calling.
10982 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10983
10984 QualType objectType = op->getLHS()->getType();
10985 if (op->getOpcode() == BO_PtrMemI)
10986 objectType = objectType->castAs<PointerType>()->getPointeeType();
10987 Qualifiers objectQuals = objectType.getQualifiers();
10988
10989 Qualifiers difference = objectQuals - funcQuals;
10990 difference.removeObjCGCAttr();
10991 difference.removeAddressSpace();
10992 if (difference) {
10993 std::string qualsString = difference.getAsString();
10994 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10995 << fnType.getUnqualifiedType()
10996 << qualsString
10997 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10998 }
10999
11000 CXXMemberCallExpr *call
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011001 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall864c0412011-04-26 20:42:42 +000011002 resultType, valueKind, RParenLoc);
11003
11004 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +000011005 op->getRHS()->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +000011006 call, 0))
11007 return ExprError();
11008
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011009 if (ConvertArgumentsForCall(call, op, 0, proto, Args, RParenLoc))
John McCall864c0412011-04-26 20:42:42 +000011010 return ExprError();
11011
Richard Trieue2a90b82013-06-22 02:30:38 +000011012 if (CheckOtherCall(call, proto))
11013 return ExprError();
11014
John McCall864c0412011-04-26 20:42:42 +000011015 return MaybeBindToTemporary(call);
11016 }
11017
John McCall5acb0c92011-10-17 18:40:02 +000011018 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011019 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall5acb0c92011-10-17 18:40:02 +000011020 return ExprError();
11021
John McCall129e2df2009-11-30 22:42:35 +000011022 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +000011023 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +000011024 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +000011025 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +000011026 if (isa<MemberExpr>(NakedMemExpr)) {
11027 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +000011028 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +000011029 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +000011030 Qualifier = MemExpr->getQualifier();
John McCall5acb0c92011-10-17 18:40:02 +000011031 UnbridgedCasts.restore();
John McCall129e2df2009-11-30 22:42:35 +000011032 } else {
11033 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +000011034 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011035
John McCall701c89e2009-12-03 04:06:58 +000011036 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011037 Expr::Classification ObjectClassification
11038 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11039 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +000011040
Douglas Gregor88a35142008-12-22 05:46:06 +000011041 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +000011042 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +000011043
John McCallaa81e162009-12-01 22:10:20 +000011044 // FIXME: avoid copy.
11045 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11046 if (UnresExpr->hasExplicitTemplateArgs()) {
11047 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11048 TemplateArgs = &TemplateArgsBuffer;
11049 }
11050
John McCall129e2df2009-11-30 22:42:35 +000011051 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11052 E = UnresExpr->decls_end(); I != E; ++I) {
11053
John McCall701c89e2009-12-03 04:06:58 +000011054 NamedDecl *Func = *I;
11055 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11056 if (isa<UsingShadowDecl>(Func))
11057 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11058
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011059
Francois Pichetdbee3412011-01-18 05:04:39 +000011060 // Microsoft supports direct constructor calls.
David Blaikie4e4d0842012-03-11 07:00:24 +000011061 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charles13a140c2012-02-25 11:00:22 +000011062 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011063 Args, CandidateSet);
Francois Pichetdbee3412011-01-18 05:04:39 +000011064 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000011065 // If explicit template arguments were provided, we can't call a
11066 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +000011067 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000011068 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011069
John McCall9aa472c2010-03-19 07:35:19 +000011070 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011071 ObjectClassification, Args, CandidateSet,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011072 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000011073 } else {
John McCall129e2df2009-11-30 22:42:35 +000011074 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +000011075 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011076 ObjectType, ObjectClassification,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011077 Args, CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +000011078 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000011079 }
Douglas Gregordec06662009-08-21 18:42:58 +000011080 }
Mike Stump1eb44332009-09-09 15:08:12 +000011081
John McCall129e2df2009-11-30 22:42:35 +000011082 DeclarationName DeclName = UnresExpr->getMemberName();
11083
John McCall5acb0c92011-10-17 18:40:02 +000011084 UnbridgedCasts.restore();
11085
Douglas Gregor88a35142008-12-22 05:46:06 +000011086 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000011087 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +000011088 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +000011089 case OR_Success:
11090 Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +000011091 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +000011092 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +000011093 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11094 return ExprError();
Faisal Valid570a922013-06-15 11:54:37 +000011095 // If FoundDecl is different from Method (such as if one is a template
11096 // and the other a specialization), make sure DiagnoseUseOfDecl is
11097 // called on both.
11098 // FIXME: This would be more comprehensively addressed by modifying
11099 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11100 // being used.
11101 if (Method != FoundDecl.getDecl() &&
11102 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11103 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000011104 break;
11105
11106 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +000011107 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +000011108 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000011109 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011110 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor88a35142008-12-22 05:46:06 +000011111 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000011112 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000011113
11114 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +000011115 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000011116 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011117 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor88a35142008-12-22 05:46:06 +000011118 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000011119 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011120
11121 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +000011122 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011123 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011124 << DeclName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011125 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011126 << MemExprE->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011127 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011128 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000011129 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000011130 }
11131
John McCall6bb80172010-03-30 21:47:33 +000011132 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +000011133
John McCallaa81e162009-12-01 22:10:20 +000011134 // If overload resolution picked a static member, build a
11135 // non-member call based on that function.
11136 if (Method->isStatic()) {
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011137 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11138 RParenLoc);
John McCallaa81e162009-12-01 22:10:20 +000011139 }
11140
John McCall129e2df2009-11-30 22:42:35 +000011141 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +000011142 }
11143
John McCallf89e55a2010-11-18 06:31:45 +000011144 QualType ResultType = Method->getResultType();
11145 ExprValueKind VK = Expr::getValueKindForType(ResultType);
11146 ResultType = ResultType.getNonLValueExprType(Context);
11147
Douglas Gregor88a35142008-12-22 05:46:06 +000011148 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011149 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011150 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCallf89e55a2010-11-18 06:31:45 +000011151 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +000011152
Anders Carlssoneed3e692009-10-10 00:06:20 +000011153 // Check for a valid return type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011154 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +000011155 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +000011156 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011157
Douglas Gregor88a35142008-12-22 05:46:06 +000011158 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +000011159 // We only need to do this if there was actually an overload; otherwise
11160 // it was done at lookup.
John Wiegley429bb272011-04-08 18:41:53 +000011161 if (!Method->isStatic()) {
11162 ExprResult ObjectArg =
11163 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11164 FoundDecl, Method);
11165 if (ObjectArg.isInvalid())
11166 return ExprError();
11167 MemExpr->setBase(ObjectArg.take());
11168 }
Douglas Gregor88a35142008-12-22 05:46:06 +000011169
11170 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +000011171 const FunctionProtoType *Proto =
11172 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011173 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor88a35142008-12-22 05:46:06 +000011174 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +000011175 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000011176
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011177 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmane61eb042012-02-18 04:48:30 +000011178
Richard Smith831421f2012-06-25 20:30:08 +000011179 if (CheckFunctionCall(Method, TheCall, Proto))
John McCallaa81e162009-12-01 22:10:20 +000011180 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +000011181
Anders Carlsson2174d4c2011-05-06 14:25:31 +000011182 if ((isa<CXXConstructorDecl>(CurContext) ||
11183 isa<CXXDestructorDecl>(CurContext)) &&
11184 TheCall->getMethodDecl()->isPure()) {
11185 const CXXMethodDecl *MD = TheCall->getMethodDecl();
11186
Chandler Carruthae198062011-06-27 08:31:58 +000011187 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson2174d4c2011-05-06 14:25:31 +000011188 Diag(MemExpr->getLocStart(),
11189 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11190 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11191 << MD->getParent()->getDeclName();
11192
11193 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruthae198062011-06-27 08:31:58 +000011194 }
Anders Carlsson2174d4c2011-05-06 14:25:31 +000011195 }
John McCall9ae2f072010-08-23 23:25:46 +000011196 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +000011197}
11198
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011199/// BuildCallToObjectOfClassType - Build a call to an object of class
11200/// type (C++ [over.call.object]), which can end up invoking an
11201/// overloaded function call operator (@c operator()) or performing a
11202/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +000011203ExprResult
John Wiegley429bb272011-04-08 18:41:53 +000011204Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregor5c37de72008-12-06 00:22:45 +000011205 SourceLocation LParenLoc,
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011206 MultiExprArg Args,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011207 SourceLocation RParenLoc) {
John McCall5acb0c92011-10-17 18:40:02 +000011208 if (checkPlaceholderForOverload(*this, Obj))
11209 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011210 ExprResult Object = Owned(Obj);
John McCall5acb0c92011-10-17 18:40:02 +000011211
11212 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011213 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall5acb0c92011-10-17 18:40:02 +000011214 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000011215
John Wiegley429bb272011-04-08 18:41:53 +000011216 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
11217 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +000011218
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011219 // C++ [over.call.object]p1:
11220 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +000011221 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011222 // candidate functions includes at least the function call
11223 // operators of T. The function call operators of T are obtained by
11224 // ordinary lookup of the name operator() in the context of
11225 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +000011226 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +000011227 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +000011228
John Wiegley429bb272011-04-08 18:41:53 +000011229 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000011230 diag::err_incomplete_object_call, Object.get()))
Douglas Gregor593564b2009-11-15 07:48:03 +000011231 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011232
John McCalla24dc2e2009-11-17 02:14:36 +000011233 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11234 LookupQualifiedName(R, Record->getDecl());
11235 R.suppressDiagnostics();
11236
Douglas Gregor593564b2009-11-15 07:48:03 +000011237 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +000011238 Oper != OperEnd; ++Oper) {
John Wiegley429bb272011-04-08 18:41:53 +000011239 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011240 Object.get()->Classify(Context),
11241 Args, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +000011242 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +000011243 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011244
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011245 // C++ [over.call.object]p2:
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011246 // In addition, for each (non-explicit in C++0x) conversion function
11247 // declared in T of the form
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011248 //
11249 // operator conversion-type-id () cv-qualifier;
11250 //
11251 // where cv-qualifier is the same cv-qualification as, or a
11252 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +000011253 // denotes the type "pointer to function of (P1,...,Pn) returning
11254 // R", or the type "reference to pointer to function of
11255 // (P1,...,Pn) returning R", or the type "reference to function
11256 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011257 // is also considered as a candidate function. Similarly,
11258 // surrogate call functions are added to the set of candidate
11259 // functions for each conversion function declared in an
11260 // accessible base class provided the function is not hidden
11261 // within T by another intervening declaration.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000011262 std::pair<CXXRecordDecl::conversion_iterator,
11263 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregor90073282010-01-11 19:36:35 +000011264 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000011265 for (CXXRecordDecl::conversion_iterator
11266 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +000011267 NamedDecl *D = *I;
11268 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11269 if (isa<UsingShadowDecl>(D))
11270 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011271
Douglas Gregor4a27d702009-10-21 06:18:39 +000011272 // Skip over templated conversion functions; they aren't
11273 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +000011274 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +000011275 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +000011276
John McCall701c89e2009-12-03 04:06:58 +000011277 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011278 if (!Conv->isExplicit()) {
11279 // Strip the reference type (if any) and then the pointer type (if
11280 // any) to get down to what might be a function type.
11281 QualType ConvType = Conv->getConversionType().getNonReferenceType();
11282 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11283 ConvType = ConvPtrType->getPointeeType();
John McCallba135432009-11-21 08:51:07 +000011284
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011285 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11286 {
11287 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011288 Object.get(), Args, CandidateSet);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011289 }
11290 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011291 }
Mike Stump1eb44332009-09-09 15:08:12 +000011292
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011293 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11294
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011295 // Perform overload resolution.
11296 OverloadCandidateSet::iterator Best;
John Wiegley429bb272011-04-08 18:41:53 +000011297 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall120d63c2010-08-24 20:38:10 +000011298 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011299 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011300 // Overload resolution succeeded; we'll build the appropriate call
11301 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011302 break;
11303
11304 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +000011305 if (CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +000011306 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley429bb272011-04-08 18:41:53 +000011307 << Object.get()->getType() << /*call*/ 1
11308 << Object.get()->getSourceRange();
John McCall1eb3e102010-01-07 02:04:15 +000011309 else
Daniel Dunbar96a00142012-03-09 18:35:03 +000011310 Diag(Object.get()->getLocStart(),
John McCall1eb3e102010-01-07 02:04:15 +000011311 diag::err_ovl_no_viable_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000011312 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011313 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011314 break;
11315
11316 case OR_Ambiguous:
Daniel Dunbar96a00142012-03-09 18:35:03 +000011317 Diag(Object.get()->getLocStart(),
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011318 diag::err_ovl_ambiguous_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000011319 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011320 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011321 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011322
11323 case OR_Deleted:
Daniel Dunbar96a00142012-03-09 18:35:03 +000011324 Diag(Object.get()->getLocStart(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011325 diag::err_ovl_deleted_object_call)
11326 << Best->Function->isDeleted()
John Wiegley429bb272011-04-08 18:41:53 +000011327 << Object.get()->getType()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011328 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley429bb272011-04-08 18:41:53 +000011329 << Object.get()->getSourceRange();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011330 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011331 break;
Mike Stump1eb44332009-09-09 15:08:12 +000011332 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011333
Douglas Gregorff331c12010-07-25 18:17:45 +000011334 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011335 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011336
John McCall5acb0c92011-10-17 18:40:02 +000011337 UnbridgedCasts.restore();
11338
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011339 if (Best->Function == 0) {
11340 // Since there is no function declaration, this is one of the
11341 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +000011342 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011343 = cast<CXXConversionDecl>(
11344 Best->Conversions[0].UserDefined.ConversionFunction);
11345
John Wiegley429bb272011-04-08 18:41:53 +000011346 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +000011347 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11348 return ExprError();
Faisal Valid570a922013-06-15 11:54:37 +000011349 assert(Conv == Best->FoundDecl.getDecl() &&
11350 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011351 // We selected one of the surrogate functions that converts the
11352 // object parameter to a function pointer. Perform the conversion
11353 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011354
Fariborz Jahaniand8307b12009-09-28 18:35:46 +000011355 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +000011356 // and then call it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011357 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11358 Conv, HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +000011359 if (Call.isInvalid())
11360 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +000011361 // Record usage of conversion in an implicit cast.
11362 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
11363 CK_UserDefinedConversion,
11364 Call.get(), 0, VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011365
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011366 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011367 }
11368
John Wiegley429bb272011-04-08 18:41:53 +000011369 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall41d89032010-01-28 01:54:34 +000011370
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011371 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11372 // that calls this method, using Object for the implicit object
11373 // parameter and passing along the remaining arguments.
11374 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Webere0ff6902012-11-09 06:06:14 +000011375
11376 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber1a52a4d2012-11-09 08:38:04 +000011377 if (Method->isInvalidDecl())
Nico Webere0ff6902012-11-09 06:06:14 +000011378 return ExprError();
11379
Chandler Carruth6df868e2010-12-12 08:17:55 +000011380 const FunctionProtoType *Proto =
11381 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011382
11383 unsigned NumArgsInProto = Proto->getNumArgs();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011384 unsigned NumArgsToCheck = Args.size();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011385
11386 // Build the full argument list for the method call (the
11387 // implicit object parameter is placed at the beginning of the
11388 // list).
11389 Expr **MethodArgs;
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011390 if (Args.size() < NumArgsInProto) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011391 NumArgsToCheck = NumArgsInProto;
11392 MethodArgs = new Expr*[NumArgsInProto + 1];
11393 } else {
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011394 MethodArgs = new Expr*[Args.size() + 1];
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011395 }
John Wiegley429bb272011-04-08 18:41:53 +000011396 MethodArgs[0] = Object.get();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011397 for (unsigned ArgIdx = 0, e = Args.size(); ArgIdx != e; ++ArgIdx)
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011398 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +000011399
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011400 DeclarationNameInfo OpLocInfo(
11401 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11402 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011403 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011404 HadMultipleCandidates,
11405 OpLocInfo.getLoc(),
11406 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000011407 if (NewFn.isInvalid())
11408 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011409
11410 // Once we've built TheCall, all of the expressions are properly
11411 // owned.
John McCallf89e55a2010-11-18 06:31:45 +000011412 QualType ResultTy = Method->getResultType();
11413 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11414 ResultTy = ResultTy.getNonLValueExprType(Context);
11415
John McCall9ae2f072010-08-23 23:25:46 +000011416 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011417 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011418 llvm::makeArrayRef(MethodArgs, Args.size()+1),
Lang Hamesbe9af122012-10-02 04:45:10 +000011419 ResultTy, VK, RParenLoc, false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011420 delete [] MethodArgs;
11421
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011422 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +000011423 Method))
11424 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011425
Douglas Gregor518fda12009-01-13 05:10:00 +000011426 // We may have default arguments. If so, we need to allocate more
11427 // slots in the call for them.
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011428 if (Args.size() < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +000011429 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011430 else if (Args.size() > NumArgsInProto)
Douglas Gregor518fda12009-01-13 05:10:00 +000011431 NumArgsToCheck = NumArgsInProto;
11432
Chris Lattner312531a2009-04-12 08:11:20 +000011433 bool IsError = false;
11434
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011435 // Initialize the implicit object parameter.
John Wiegley429bb272011-04-08 18:41:53 +000011436 ExprResult ObjRes =
11437 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11438 Best->FoundDecl, Method);
11439 if (ObjRes.isInvalid())
11440 IsError = true;
11441 else
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011442 Object = ObjRes;
John Wiegley429bb272011-04-08 18:41:53 +000011443 TheCall->setArg(0, Object.take());
Chris Lattner312531a2009-04-12 08:11:20 +000011444
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011445 // Check the argument types.
11446 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011447 Expr *Arg;
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011448 if (i < Args.size()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011449 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +000011450
Douglas Gregor518fda12009-01-13 05:10:00 +000011451 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +000011452
John McCall60d7b3a2010-08-24 06:29:42 +000011453 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +000011454 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000011455 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +000011456 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +000011457 SourceLocation(), Arg);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011458
Anders Carlsson3faa4862010-01-29 18:43:53 +000011459 IsError |= InputInit.isInvalid();
11460 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011461 } else {
John McCall60d7b3a2010-08-24 06:29:42 +000011462 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +000011463 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11464 if (DefArg.isInvalid()) {
11465 IsError = true;
11466 break;
11467 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011468
Douglas Gregord47c47d2009-11-09 19:27:57 +000011469 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011470 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011471
11472 TheCall->setArg(i + 1, Arg);
11473 }
11474
11475 // If this is a variadic call, handle args passed through "...".
11476 if (Proto->isVariadic()) {
11477 // Promote the arguments (C99 6.5.2.2p7).
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011478 for (unsigned i = NumArgsInProto, e = Args.size(); i < e; i++) {
John Wiegley429bb272011-04-08 18:41:53 +000011479 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11480 IsError |= Arg.isInvalid();
11481 TheCall->setArg(i + 1, Arg.take());
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011482 }
11483 }
11484
Chris Lattner312531a2009-04-12 08:11:20 +000011485 if (IsError) return true;
11486
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011487 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmane61eb042012-02-18 04:48:30 +000011488
Richard Smith831421f2012-06-25 20:30:08 +000011489 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +000011490 return true;
11491
John McCall182f7092010-08-24 06:09:16 +000011492 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011493}
11494
Douglas Gregor8ba10742008-11-20 16:27:02 +000011495/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +000011496/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +000011497/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +000011498ExprResult
Kaelyn Uhrainbaaeb852013-07-31 17:38:24 +000011499Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
11500 bool *NoArrowOperatorFound) {
Chandler Carruth6df868e2010-12-12 08:17:55 +000011501 assert(Base->getType()->isRecordType() &&
11502 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +000011503
John McCall5acb0c92011-10-17 18:40:02 +000011504 if (checkPlaceholderForOverload(*this, Base))
11505 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000011506
John McCall5769d612010-02-08 23:07:23 +000011507 SourceLocation Loc = Base->getExprLoc();
11508
Douglas Gregor8ba10742008-11-20 16:27:02 +000011509 // C++ [over.ref]p1:
11510 //
11511 // [...] An expression x->m is interpreted as (x.operator->())->m
11512 // for a class object x of type T if T::operator->() exists and if
11513 // the operator is selected as the best match function by the
11514 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +000011515 DeclarationName OpName =
11516 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +000011517 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +000011518 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011519
John McCall5769d612010-02-08 23:07:23 +000011520 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000011521 diag::err_typecheck_incomplete_tag, Base))
Eli Friedmanf43fb722009-11-18 01:28:03 +000011522 return ExprError();
11523
John McCalla24dc2e2009-11-17 02:14:36 +000011524 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11525 LookupQualifiedName(R, BaseRecord->getDecl());
11526 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +000011527
11528 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +000011529 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011530 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko55431692013-05-05 00:41:58 +000011531 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +000011532 }
Douglas Gregor8ba10742008-11-20 16:27:02 +000011533
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011534 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11535
Douglas Gregor8ba10742008-11-20 16:27:02 +000011536 // Perform overload resolution.
11537 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000011538 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +000011539 case OR_Success:
11540 // Overload resolution succeeded; we'll build the call below.
11541 break;
11542
11543 case OR_No_Viable_Function:
Kaelyn Uhrain45c3ba72013-07-11 22:38:30 +000011544 if (CandidateSet.empty()) {
11545 QualType BaseType = Base->getType();
Kaelyn Uhrainbaaeb852013-07-31 17:38:24 +000011546 if (NoArrowOperatorFound) {
11547 // Report this specific error to the caller instead of emitting a
11548 // diagnostic, as requested.
11549 *NoArrowOperatorFound = true;
11550 return ExprError();
11551 }
Kaelyn Uhraind4224342013-07-15 19:54:54 +000011552 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
11553 << BaseType << Base->getSourceRange();
Kaelyn Uhrain45c3ba72013-07-11 22:38:30 +000011554 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhraind4224342013-07-15 19:54:54 +000011555 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain45c3ba72013-07-11 22:38:30 +000011556 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain45c3ba72013-07-11 22:38:30 +000011557 }
11558 } else
Douglas Gregor8ba10742008-11-20 16:27:02 +000011559 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011560 << "operator->" << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011561 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011562 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011563
11564 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000011565 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11566 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011567 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011568 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011569
11570 case OR_Deleted:
11571 Diag(OpLoc, diag::err_ovl_deleted_oper)
11572 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011573 << "->"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011574 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011575 << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011576 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011577 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011578 }
11579
John McCall9aa472c2010-03-19 07:35:19 +000011580 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
11581
Douglas Gregor8ba10742008-11-20 16:27:02 +000011582 // Convert the object parameter.
11583 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000011584 ExprResult BaseResult =
11585 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11586 Best->FoundDecl, Method);
11587 if (BaseResult.isInvalid())
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011588 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011589 Base = BaseResult.take();
Douglas Gregorfc195ef2008-11-21 03:04:22 +000011590
Douglas Gregor8ba10742008-11-20 16:27:02 +000011591 // Build the operator call.
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011592 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011593 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000011594 if (FnExpr.isInvalid())
11595 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011596
John McCallf89e55a2010-11-18 06:31:45 +000011597 QualType ResultTy = Method->getResultType();
11598 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11599 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +000011600 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011601 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000011602 Base, ResultTy, VK, OpLoc, false);
Anders Carlsson15ea3782009-10-13 22:43:21 +000011603
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011604 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000011605 Method))
11606 return ExprError();
Eli Friedmand5931902011-04-04 01:18:25 +000011607
11608 return MaybeBindToTemporary(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +000011609}
11610
Richard Smith36f5cfe2012-03-09 08:00:36 +000011611/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11612/// a literal operator described by the provided lookup results.
11613ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11614 DeclarationNameInfo &SuffixInfo,
11615 ArrayRef<Expr*> Args,
11616 SourceLocation LitEndLoc,
11617 TemplateArgumentListInfo *TemplateArgs) {
11618 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smith9fcce652012-03-07 08:35:16 +000011619
Richard Smith36f5cfe2012-03-09 08:00:36 +000011620 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11621 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11622 TemplateArgs);
Richard Smith9fcce652012-03-07 08:35:16 +000011623
Richard Smith36f5cfe2012-03-09 08:00:36 +000011624 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11625
Richard Smith36f5cfe2012-03-09 08:00:36 +000011626 // Perform overload resolution. This will usually be trivial, but might need
11627 // to perform substitutions for a literal operator template.
11628 OverloadCandidateSet::iterator Best;
11629 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11630 case OR_Success:
11631 case OR_Deleted:
11632 break;
11633
11634 case OR_No_Viable_Function:
11635 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11636 << R.getLookupName();
11637 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11638 return ExprError();
11639
11640 case OR_Ambiguous:
11641 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11642 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11643 return ExprError();
Richard Smith9fcce652012-03-07 08:35:16 +000011644 }
11645
Richard Smith36f5cfe2012-03-09 08:00:36 +000011646 FunctionDecl *FD = Best->Function;
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011647 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
11648 HadMultipleCandidates,
Richard Smith36f5cfe2012-03-09 08:00:36 +000011649 SuffixInfo.getLoc(),
11650 SuffixInfo.getInfo());
11651 if (Fn.isInvalid())
11652 return true;
Richard Smith9fcce652012-03-07 08:35:16 +000011653
11654 // Check the argument types. This should almost always be a no-op, except
11655 // that array-to-pointer decay is applied to string literals.
Richard Smith9fcce652012-03-07 08:35:16 +000011656 Expr *ConvArgs[2];
Richard Smith958ba642013-05-05 15:51:06 +000011657 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smith9fcce652012-03-07 08:35:16 +000011658 ExprResult InputInit = PerformCopyInitialization(
11659 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11660 SourceLocation(), Args[ArgIdx]);
11661 if (InputInit.isInvalid())
11662 return true;
11663 ConvArgs[ArgIdx] = InputInit.take();
11664 }
11665
Richard Smith9fcce652012-03-07 08:35:16 +000011666 QualType ResultTy = FD->getResultType();
11667 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11668 ResultTy = ResultTy.getNonLValueExprType(Context);
11669
Richard Smith9fcce652012-03-07 08:35:16 +000011670 UserDefinedLiteral *UDL =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000011671 new (Context) UserDefinedLiteral(Context, Fn.take(),
11672 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smith9fcce652012-03-07 08:35:16 +000011673 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11674
11675 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11676 return ExprError();
11677
Richard Smith831421f2012-06-25 20:30:08 +000011678 if (CheckFunctionCall(FD, UDL, NULL))
Richard Smith9fcce652012-03-07 08:35:16 +000011679 return ExprError();
11680
11681 return MaybeBindToTemporary(UDL);
11682}
11683
Sam Panzere1715b62012-08-21 00:52:01 +000011684/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11685/// given LookupResult is non-empty, it is assumed to describe a member which
11686/// will be invoked. Otherwise, the function will be found via argument
11687/// dependent lookup.
11688/// CallExpr is set to a valid expression and FRS_Success returned on success,
11689/// otherwise CallExpr is set to ExprError() and some non-success value
11690/// is returned.
11691Sema::ForRangeStatus
11692Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11693 SourceLocation RangeLoc, VarDecl *Decl,
11694 BeginEndFunction BEF,
11695 const DeclarationNameInfo &NameInfo,
11696 LookupResult &MemberLookup,
11697 OverloadCandidateSet *CandidateSet,
11698 Expr *Range, ExprResult *CallExpr) {
11699 CandidateSet->clear();
11700 if (!MemberLookup.empty()) {
11701 ExprResult MemberRef =
11702 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11703 /*IsPtr=*/false, CXXScopeSpec(),
11704 /*TemplateKWLoc=*/SourceLocation(),
11705 /*FirstQualifierInScope=*/0,
11706 MemberLookup,
11707 /*TemplateArgs=*/0);
11708 if (MemberRef.isInvalid()) {
11709 *CallExpr = ExprError();
11710 Diag(Range->getLocStart(), diag::note_in_for_range)
11711 << RangeLoc << BEF << Range->getType();
11712 return FRS_DiagnosticIssued;
11713 }
Dmitri Gribenko62ed8892013-05-05 20:40:26 +000011714 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, 0);
Sam Panzere1715b62012-08-21 00:52:01 +000011715 if (CallExpr->isInvalid()) {
11716 *CallExpr = ExprError();
11717 Diag(Range->getLocStart(), diag::note_in_for_range)
11718 << RangeLoc << BEF << Range->getType();
11719 return FRS_DiagnosticIssued;
11720 }
11721 } else {
11722 UnresolvedSet<0> FoundNames;
Sam Panzere1715b62012-08-21 00:52:01 +000011723 UnresolvedLookupExpr *Fn =
11724 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11725 NestedNameSpecifierLoc(), NameInfo,
11726 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb1502bc2012-10-18 17:56:02 +000011727 FoundNames.begin(), FoundNames.end());
Sam Panzere1715b62012-08-21 00:52:01 +000011728
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011729 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzere1715b62012-08-21 00:52:01 +000011730 CandidateSet, CallExpr);
11731 if (CandidateSet->empty() || CandidateSetError) {
11732 *CallExpr = ExprError();
11733 return FRS_NoViableFunction;
11734 }
11735 OverloadCandidateSet::iterator Best;
11736 OverloadingResult OverloadResult =
11737 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
11738
11739 if (OverloadResult == OR_No_Viable_Function) {
11740 *CallExpr = ExprError();
11741 return FRS_NoViableFunction;
11742 }
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011743 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Sam Panzere1715b62012-08-21 00:52:01 +000011744 Loc, 0, CandidateSet, &Best,
11745 OverloadResult,
11746 /*AllowTypoCorrection=*/false);
11747 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
11748 *CallExpr = ExprError();
11749 Diag(Range->getLocStart(), diag::note_in_for_range)
11750 << RangeLoc << BEF << Range->getType();
11751 return FRS_DiagnosticIssued;
11752 }
11753 }
11754 return FRS_Success;
11755}
11756
11757
Douglas Gregor904eed32008-11-10 20:40:00 +000011758/// FixOverloadedFunctionReference - E is an expression that refers to
11759/// a C++ overloaded function (possibly with some parentheses and
11760/// perhaps a '&' around it). We have resolved the overloaded function
11761/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +000011762/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +000011763Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +000011764 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +000011765 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011766 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11767 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011768 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011769 return PE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011770
Douglas Gregor699ee522009-11-20 19:42:02 +000011771 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011772 }
11773
Douglas Gregor699ee522009-11-20 19:42:02 +000011774 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011775 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11776 Found, Fn);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011777 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +000011778 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +000011779 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +000011780 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +000011781 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011782 return ICE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011783
11784 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallf871d0c2010-08-07 06:22:56 +000011785 ICE->getCastKind(),
11786 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +000011787 ICE->getValueKind());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011788 }
11789
Douglas Gregor699ee522009-11-20 19:42:02 +000011790 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +000011791 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +000011792 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +000011793 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11794 if (Method->isStatic()) {
11795 // Do nothing: static member functions aren't any different
11796 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +000011797 } else {
John McCallf7a1a742009-11-24 19:00:30 +000011798 // Fix the sub expression, which really has to be an
11799 // UnresolvedLookupExpr holding an overloaded member function
11800 // or template.
John McCall6bb80172010-03-30 21:47:33 +000011801 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11802 Found, Fn);
John McCallba135432009-11-21 08:51:07 +000011803 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011804 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +000011805
John McCallba135432009-11-21 08:51:07 +000011806 assert(isa<DeclRefExpr>(SubExpr)
11807 && "fixed to something other than a decl ref");
11808 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11809 && "fixed to a member ref with no nested name qualifier");
11810
11811 // We have taken the address of a pointer to member
11812 // function. Perform the computation here so that we get the
11813 // appropriate pointer to member type.
11814 QualType ClassType
11815 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11816 QualType MemPtrType
11817 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11818
John McCallf89e55a2010-11-18 06:31:45 +000011819 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11820 VK_RValue, OK_Ordinary,
11821 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +000011822 }
11823 }
John McCall6bb80172010-03-30 21:47:33 +000011824 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11825 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011826 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011827 return UnOp;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011828
John McCall2de56d12010-08-25 11:45:40 +000011829 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +000011830 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +000011831 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +000011832 UnOp->getOperatorLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011833 }
John McCallba135432009-11-21 08:51:07 +000011834
11835 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +000011836 // FIXME: avoid copy.
11837 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +000011838 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +000011839 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11840 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +000011841 }
11842
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011843 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11844 ULE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011845 ULE->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011846 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011847 /*enclosing*/ false, // FIXME?
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011848 ULE->getNameLoc(),
11849 Fn->getType(),
11850 VK_LValue,
11851 Found.getDecl(),
11852 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011853 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011854 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11855 return DRE;
John McCallba135432009-11-21 08:51:07 +000011856 }
11857
John McCall129e2df2009-11-30 22:42:35 +000011858 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +000011859 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +000011860 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11861 if (MemExpr->hasExplicitTemplateArgs()) {
11862 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11863 TemplateArgs = &TemplateArgsBuffer;
11864 }
John McCalld5532b62009-11-23 01:53:49 +000011865
John McCallaa81e162009-12-01 22:10:20 +000011866 Expr *Base;
11867
John McCallf89e55a2010-11-18 06:31:45 +000011868 // If we're filling in a static method where we used to have an
11869 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +000011870 if (MemExpr->isImplicitAccess()) {
11871 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011872 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11873 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011874 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011875 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011876 /*enclosing*/ false,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011877 MemExpr->getMemberLoc(),
11878 Fn->getType(),
11879 VK_LValue,
11880 Found.getDecl(),
11881 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011882 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011883 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11884 return DRE;
Douglas Gregor828a1972010-01-07 23:12:05 +000011885 } else {
11886 SourceLocation Loc = MemExpr->getMemberLoc();
11887 if (MemExpr->getQualifier())
Douglas Gregor4c9be892011-02-28 20:01:57 +000011888 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman72899c32012-01-07 04:59:52 +000011889 CheckCXXThisCapture(Loc);
Douglas Gregor828a1972010-01-07 23:12:05 +000011890 Base = new (Context) CXXThisExpr(Loc,
11891 MemExpr->getBaseType(),
11892 /*isImplicit=*/true);
11893 }
John McCallaa81e162009-12-01 22:10:20 +000011894 } else
John McCall3fa5cae2010-10-26 07:05:15 +000011895 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +000011896
John McCallf5307512011-04-27 00:36:17 +000011897 ExprValueKind valueKind;
11898 QualType type;
11899 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11900 valueKind = VK_LValue;
11901 type = Fn->getType();
11902 } else {
11903 valueKind = VK_RValue;
11904 type = Context.BoundMemberTy;
11905 }
11906
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011907 MemberExpr *ME = MemberExpr::Create(Context, Base,
11908 MemExpr->isArrow(),
11909 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011910 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011911 Fn,
11912 Found,
11913 MemExpr->getMemberNameInfo(),
11914 TemplateArgs,
11915 type, valueKind, OK_Ordinary);
11916 ME->setHadMultipleCandidates(true);
Richard Smith4a030222012-11-14 07:06:31 +000011917 MarkMemberReferenced(ME);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011918 return ME;
Douglas Gregor699ee522009-11-20 19:42:02 +000011919 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011920
John McCall3fa5cae2010-10-26 07:05:15 +000011921 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregor904eed32008-11-10 20:40:00 +000011922}
11923
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011924ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCall60d7b3a2010-08-24 06:29:42 +000011925 DeclAccessPair Found,
11926 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +000011927 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +000011928}
11929
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000011930} // end namespace clang