blob: df18752bfa8966841422e025ad01c92b49a05710 [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
Richard Smithb390e492013-09-21 21:55:46 +00005832 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
5833 // operator is only a candidate if its return type is the target type or
5834 // can be converted to the target type with a qualification conversion.
5835 bool ObjCLifetimeConversion;
5836 QualType ToNonRefType = ToType.getNonReferenceType();
5837 if (Conversion->isExplicit() &&
5838 !Context.hasSameUnqualifiedType(ConvType, ToNonRefType) &&
5839 !IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
5840 ObjCLifetimeConversion))
5841 return;
5842
Douglas Gregor7edfb692009-11-23 12:27:39 +00005843 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005844 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005845
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005846 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005847 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCall9aa472c2010-03-19 07:35:19 +00005848 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005849 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005850 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005851 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005852 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005853 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00005854 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005855 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005856 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005857
Douglas Gregorbca39322010-08-19 15:37:02 +00005858 // C++ [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005859 // For conversion functions, the function is considered to be a member of
5860 // the class of the implicit implied object argument for the purpose of
Douglas Gregorbca39322010-08-19 15:37:02 +00005861 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005862 //
5863 // Determine the implicit conversion sequence for the implicit
5864 // object parameter.
5865 QualType ImplicitParamType = From->getType();
5866 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5867 ImplicitParamType = FromPtrType->getPointeeType();
5868 CXXRecordDecl *ConversionContext
5869 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005870
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005871 Candidate.Conversions[0]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005872 = TryObjectArgumentInitialization(*this, From->getType(),
5873 From->Classify(Context),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005874 Conversion, ConversionContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005875
John McCall1d318332010-01-12 00:44:57 +00005876 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005877 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005878 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005879 return;
5880 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005881
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005882 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005883 // derived to base as such conversions are given Conversion Rank. They only
5884 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5885 QualType FromCanon
5886 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5887 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5888 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5889 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005890 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005891 return;
5892 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005893
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005894 // To determine what the conversion from the result of calling the
5895 // conversion function to the type we're eventually trying to
5896 // convert to (ToType), we need to synthesize a call to the
5897 // conversion function and attempt copy initialization from it. This
5898 // makes sure that we get the right semantics with respect to
5899 // lvalues/rvalues and the type. Fortunately, we can allocate this
5900 // call on the stack and we don't need its arguments to be
5901 // well-formed.
John McCallf4b88a42012-03-10 09:33:50 +00005902 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005903 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00005904 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5905 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00005906 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00005907 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00005908
Richard Smith87c1f1f2011-07-13 22:53:21 +00005909 QualType ConversionType = Conversion->getConversionType();
5910 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor7d14d382010-11-13 19:36:57 +00005911 Candidate.Viable = false;
5912 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5913 return;
5914 }
5915
Richard Smith87c1f1f2011-07-13 22:53:21 +00005916 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCallf89e55a2010-11-18 06:31:45 +00005917
Mike Stump1eb44332009-09-09 15:08:12 +00005918 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00005919 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5920 // allocator).
Richard Smith87c1f1f2011-07-13 22:53:21 +00005921 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00005922 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00005923 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00005924 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00005925 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005926 /*SuppressUserConversions=*/true,
John McCallf85e1932011-06-15 23:02:42 +00005927 /*InOverloadResolution=*/false,
5928 /*AllowObjCWritebackConversion=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00005929
John McCall1d318332010-01-12 00:44:57 +00005930 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005931 case ImplicitConversionSequence::StandardConversion:
5932 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005933
Douglas Gregorc520c842010-04-12 23:42:09 +00005934 // C++ [over.ics.user]p3:
5935 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005936 // conversion function template, the second standard conversion sequence
Douglas Gregorc520c842010-04-12 23:42:09 +00005937 // shall have exact match rank.
5938 if (Conversion->getPrimaryTemplate() &&
5939 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5940 Candidate.Viable = false;
5941 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5942 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005943
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005944 // C++0x [dcl.init.ref]p5:
5945 // In the second case, if the reference is an rvalue reference and
5946 // the second standard conversion sequence of the user-defined
5947 // conversion sequence includes an lvalue-to-rvalue conversion, the
5948 // program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005949 if (ToType->isRValueReferenceType() &&
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005950 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5951 Candidate.Viable = false;
5952 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5953 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005954 break;
5955
5956 case ImplicitConversionSequence::BadConversion:
5957 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005958 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005959 break;
5960
5961 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00005962 llvm_unreachable(
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005963 "Can only end up with a standard conversion sequence or failure");
5964 }
5965}
5966
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005967/// \brief Adds a conversion function template specialization
5968/// candidate to the overload set, using template argument deduction
5969/// to deduce the template arguments of the conversion function
5970/// template from the type that we are converting to (C++
5971/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00005972void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005973Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005974 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005975 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005976 Expr *From, QualType ToType,
5977 OverloadCandidateSet &CandidateSet) {
5978 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5979 "Only conversion function templates permitted here");
5980
Douglas Gregor3f396022009-09-28 04:47:19 +00005981 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5982 return;
5983
Craig Topper93e45992012-09-19 02:26:47 +00005984 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005985 CXXConversionDecl *Specialization = 0;
5986 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00005987 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005988 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005989 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005990 Candidate.FoundDecl = FoundDecl;
5991 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5992 Candidate.Viable = false;
5993 Candidate.FailureKind = ovl_fail_bad_deduction;
5994 Candidate.IsSurrogate = false;
5995 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005996 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005997 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005998 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005999 return;
6000 }
Mike Stump1eb44332009-09-09 15:08:12 +00006001
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006002 // Add the conversion function template specialization produced by
6003 // template argument deduction as a candidate.
6004 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00006005 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00006006 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006007}
6008
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006009/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6010/// converts the given @c Object to a function pointer via the
6011/// conversion function @c Conversion, and then attempts to call it
6012/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6013/// the type of function that we'll eventually be calling.
6014void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00006015 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00006016 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00006017 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006018 Expr *Object,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006019 ArrayRef<Expr *> Args,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006020 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00006021 if (!CandidateSet.isNewCandidate(Conversion))
6022 return;
6023
Douglas Gregor7edfb692009-11-23 12:27:39 +00006024 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00006025 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00006026
Ahmed Charles13a140c2012-02-25 11:00:22 +00006027 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00006028 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006029 Candidate.Function = 0;
6030 Candidate.Surrogate = Conversion;
6031 Candidate.Viable = true;
6032 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00006033 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00006034 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006035
6036 // Determine the implicit conversion sequence for the implicit
6037 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00006038 ImplicitConversionSequence ObjectInit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006039 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006040 Object->Classify(Context),
6041 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00006042 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006043 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006044 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00006045 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006046 return;
6047 }
6048
6049 // The first conversion is actually a user-defined conversion whose
6050 // first conversion is ObjectInit's standard conversion (which is
6051 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00006052 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006053 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00006054 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00006055 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006056 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00006057 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00006058 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006059 = Candidate.Conversions[0].UserDefined.Before;
6060 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6061
Mike Stump1eb44332009-09-09 15:08:12 +00006062 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006063 unsigned NumArgsInProto = Proto->getNumArgs();
6064
6065 // (C++ 13.3.2p2): A candidate function having fewer than m
6066 // parameters is viable only if it has an ellipsis in its parameter
6067 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00006068 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006069 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006070 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006071 return;
6072 }
6073
6074 // Function types don't have any default arguments, so just check if
6075 // we have enough arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00006076 if (Args.size() < NumArgsInProto) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006077 // Not enough arguments.
6078 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006079 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006080 return;
6081 }
6082
6083 // Determine the implicit conversion sequences for each of the
6084 // arguments.
Richard Smith958ba642013-05-05 15:51:06 +00006085 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006086 if (ArgIdx < NumArgsInProto) {
6087 // (C++ 13.3.2p3): for F to be a viable function, there shall
6088 // exist for each argument an implicit conversion sequence
6089 // (13.3.3.1) that converts that argument to the corresponding
6090 // parameter of F.
6091 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00006092 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006093 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00006094 /*SuppressUserConversions=*/false,
John McCallf85e1932011-06-15 23:02:42 +00006095 /*InOverloadResolution=*/false,
6096 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00006097 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00006098 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006099 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006100 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006101 break;
6102 }
6103 } else {
6104 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6105 // argument for which there is no corresponding parameter is
6106 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00006107 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006108 }
6109 }
6110}
6111
Douglas Gregor063daf62009-03-13 18:40:31 +00006112/// \brief Add overload candidates for overloaded operators that are
6113/// member functions.
6114///
6115/// Add the overloaded operator candidates that are member functions
6116/// for the operator Op that was used in an operator expression such
6117/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6118/// CandidateSet will store the added overload candidates. (C++
6119/// [over.match.oper]).
6120void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6121 SourceLocation OpLoc,
Richard Smith958ba642013-05-05 15:51:06 +00006122 ArrayRef<Expr *> Args,
Douglas Gregor063daf62009-03-13 18:40:31 +00006123 OverloadCandidateSet& CandidateSet,
6124 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00006125 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6126
6127 // C++ [over.match.oper]p3:
6128 // For a unary operator @ with an operand of a type whose
6129 // cv-unqualified version is T1, and for a binary operator @ with
6130 // a left operand of a type whose cv-unqualified version is T1 and
6131 // a right operand of a type whose cv-unqualified version is T2,
6132 // three sets of candidate functions, designated member
6133 // candidates, non-member candidates and built-in candidates, are
6134 // constructed as follows:
6135 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00006136
Richard Smithe410be92013-04-20 12:41:22 +00006137 // -- If T1 is a complete class type or a class currently being
6138 // defined, the set of member candidates is the result of the
6139 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6140 // the set of member candidates is empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00006141 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smithe410be92013-04-20 12:41:22 +00006142 // Complete the type if it can be completed.
6143 RequireCompleteType(OpLoc, T1, 0);
6144 // If the type is neither complete nor being defined, bail out now.
6145 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor8a5ae242009-08-27 23:35:55 +00006146 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006147
John McCalla24dc2e2009-11-17 02:14:36 +00006148 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6149 LookupQualifiedName(Operators, T1Rec->getDecl());
6150 Operators.suppressDiagnostics();
6151
Mike Stump1eb44332009-09-09 15:08:12 +00006152 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00006153 OperEnd = Operators.end();
6154 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00006155 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00006156 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola548107e2013-04-29 19:29:25 +00006157 Args[0]->Classify(Context),
Richard Smith958ba642013-05-05 15:51:06 +00006158 Args.slice(1),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006159 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00006160 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00006161 }
Douglas Gregor96176b32008-11-18 23:14:02 +00006162}
6163
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006164/// AddBuiltinCandidate - Add a candidate for a built-in
6165/// operator. ResultTy and ParamTys are the result and parameter types
6166/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006167/// arguments being passed to the candidate. IsAssignmentOperator
6168/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006169/// operator. NumContextualBoolArguments is the number of arguments
6170/// (at the beginning of the argument list) that will be contextually
6171/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00006172void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smith958ba642013-05-05 15:51:06 +00006173 ArrayRef<Expr *> Args,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006174 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006175 bool IsAssignmentOperator,
6176 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00006177 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00006178 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00006179
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006180 // Add this candidate
Richard Smith958ba642013-05-05 15:51:06 +00006181 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCall9aa472c2010-03-19 07:35:19 +00006182 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006183 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00006184 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00006185 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006186 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smith958ba642013-05-05 15:51:06 +00006187 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006188 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6189
6190 // Determine the implicit conversion sequences for each of the
6191 // arguments.
6192 Candidate.Viable = true;
Richard Smith958ba642013-05-05 15:51:06 +00006193 Candidate.ExplicitCallArguments = Args.size();
6194 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006195 // C++ [over.match.oper]p4:
6196 // For the built-in assignment operators, conversions of the
6197 // left operand are restricted as follows:
6198 // -- no temporaries are introduced to hold the left operand, and
6199 // -- no user-defined conversions are applied to the left
6200 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00006201 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006202 //
6203 // We block these conversions by turning off user-defined
6204 // conversions, since that is the only way that initialization of
6205 // a reference to a non-class type can occur from something that
6206 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006207 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00006208 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006209 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00006210 Candidate.Conversions[ArgIdx]
6211 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006212 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00006213 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006214 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00006215 ArgIdx == 0 && IsAssignmentOperator,
John McCallf85e1932011-06-15 23:02:42 +00006216 /*InOverloadResolution=*/false,
6217 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00006218 getLangOpts().ObjCAutoRefCount);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006219 }
John McCall1d318332010-01-12 00:44:57 +00006220 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006221 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006222 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00006223 break;
6224 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006225 }
6226}
6227
Craig Topperfe09f3f2013-07-01 06:29:40 +00006228namespace {
6229
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006230/// BuiltinCandidateTypeSet - A set of types that will be used for the
6231/// candidate operator functions for built-in operators (C++
6232/// [over.built]). The types are separated into pointer types and
6233/// enumeration types.
6234class BuiltinCandidateTypeSet {
6235 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006236 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006237
6238 /// PointerTypes - The set of pointer types that will be used in the
6239 /// built-in candidates.
6240 TypeSet PointerTypes;
6241
Sebastian Redl78eb8742009-04-19 21:53:20 +00006242 /// MemberPointerTypes - The set of member pointer types that will be
6243 /// used in the built-in candidates.
6244 TypeSet MemberPointerTypes;
6245
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006246 /// EnumerationTypes - The set of enumeration types that will be
6247 /// used in the built-in candidates.
6248 TypeSet EnumerationTypes;
6249
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006250 /// \brief The set of vector types that will be used in the built-in
Douglas Gregor26bcf672010-05-19 03:21:00 +00006251 /// candidates.
6252 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00006253
6254 /// \brief A flag indicating non-record types are viable candidates
6255 bool HasNonRecordTypes;
6256
6257 /// \brief A flag indicating whether either arithmetic or enumeration types
6258 /// were present in the candidate set.
6259 bool HasArithmeticOrEnumeralTypes;
6260
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006261 /// \brief A flag indicating whether the nullptr type was present in the
6262 /// candidate set.
6263 bool HasNullPtrType;
6264
Douglas Gregor5842ba92009-08-24 15:23:48 +00006265 /// Sema - The semantic analysis instance where we are building the
6266 /// candidate type set.
6267 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00006268
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006269 /// Context - The AST context in which we will build the type sets.
6270 ASTContext &Context;
6271
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006272 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6273 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00006274 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006275
6276public:
6277 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006278 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006279
Mike Stump1eb44332009-09-09 15:08:12 +00006280 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00006281 : HasNonRecordTypes(false),
6282 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006283 HasNullPtrType(false),
Chandler Carruth6a577462010-12-13 01:44:01 +00006284 SemaRef(SemaRef),
6285 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006286
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006287 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006288 SourceLocation Loc,
6289 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006290 bool AllowExplicitConversions,
6291 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006292
6293 /// pointer_begin - First pointer type found;
6294 iterator pointer_begin() { return PointerTypes.begin(); }
6295
Sebastian Redl78eb8742009-04-19 21:53:20 +00006296 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006297 iterator pointer_end() { return PointerTypes.end(); }
6298
Sebastian Redl78eb8742009-04-19 21:53:20 +00006299 /// member_pointer_begin - First member pointer type found;
6300 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6301
6302 /// member_pointer_end - Past the last member pointer type found;
6303 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6304
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006305 /// enumeration_begin - First enumeration type found;
6306 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6307
Sebastian Redl78eb8742009-04-19 21:53:20 +00006308 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006309 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006310
Douglas Gregor26bcf672010-05-19 03:21:00 +00006311 iterator vector_begin() { return VectorTypes.begin(); }
6312 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00006313
6314 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6315 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006316 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006317};
6318
Craig Topperfe09f3f2013-07-01 06:29:40 +00006319} // end anonymous namespace
6320
Sebastian Redl78eb8742009-04-19 21:53:20 +00006321/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006322/// the set of pointer types along with any more-qualified variants of
6323/// that type. For example, if @p Ty is "int const *", this routine
6324/// will add "int const *", "int const volatile *", "int const
6325/// restrict *", and "int const volatile restrict *" to the set of
6326/// pointer types. Returns true if the add of @p Ty itself succeeded,
6327/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006328///
6329/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006330bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00006331BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6332 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00006333
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006334 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006335 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006336 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006337
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006338 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00006339 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006340 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006341 if (!PointerTy) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006342 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6343 PointeeTy = PTy->getPointeeType();
6344 buildObjCPtr = true;
6345 } else {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006346 PointeeTy = PointerTy->getPointeeType();
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006347 }
6348
Sebastian Redla9efada2009-11-18 20:39:26 +00006349 // Don't add qualified variants of arrays. For one, they're not allowed
6350 // (the qualifier would sink to the element type), and for another, the
6351 // only overload situation where it matters is subscript or pointer +- int,
6352 // and those shouldn't have qualifier variants anyway.
6353 if (PointeeTy->isArrayType())
6354 return true;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006355
John McCall0953e762009-09-24 19:53:00 +00006356 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006357 bool hasVolatile = VisibleQuals.hasVolatile();
6358 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006359
John McCall0953e762009-09-24 19:53:00 +00006360 // Iterate through all strict supersets of BaseCVR.
6361 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6362 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006363 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006364 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006365
6366 // Skip over restrict if no restrict found anywhere in the types, or if
6367 // the type cannot be restrict-qualified.
6368 if ((CVR & Qualifiers::Restrict) &&
6369 (!hasRestrict ||
6370 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6371 continue;
6372
6373 // Build qualified pointee type.
John McCall0953e762009-09-24 19:53:00 +00006374 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006375
6376 // Build qualified pointer type.
6377 QualType QPointerTy;
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006378 if (!buildObjCPtr)
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006379 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006380 else
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006381 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6382
6383 // Insert qualified pointer type.
6384 PointerTypes.insert(QPointerTy);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006385 }
6386
6387 return true;
6388}
6389
Sebastian Redl78eb8742009-04-19 21:53:20 +00006390/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6391/// to the set of pointer types along with any more-qualified variants of
6392/// that type. For example, if @p Ty is "int const *", this routine
6393/// will add "int const *", "int const volatile *", "int const
6394/// restrict *", and "int const volatile restrict *" to the set of
6395/// pointer types. Returns true if the add of @p Ty itself succeeded,
6396/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006397///
6398/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006399bool
6400BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6401 QualType Ty) {
6402 // Insert this type.
6403 if (!MemberPointerTypes.insert(Ty))
6404 return false;
6405
John McCall0953e762009-09-24 19:53:00 +00006406 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6407 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00006408
John McCall0953e762009-09-24 19:53:00 +00006409 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00006410 // Don't add qualified variants of arrays. For one, they're not allowed
6411 // (the qualifier would sink to the element type), and for another, the
6412 // only overload situation where it matters is subscript or pointer +- int,
6413 // and those shouldn't have qualifier variants anyway.
6414 if (PointeeTy->isArrayType())
6415 return true;
John McCall0953e762009-09-24 19:53:00 +00006416 const Type *ClassTy = PointerTy->getClass();
6417
6418 // Iterate through all strict supersets of the pointee type's CVR
6419 // qualifiers.
6420 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6421 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6422 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006423
John McCall0953e762009-09-24 19:53:00 +00006424 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006425 MemberPointerTypes.insert(
6426 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00006427 }
6428
6429 return true;
6430}
6431
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006432/// AddTypesConvertedFrom - Add each of the types to which the type @p
6433/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00006434/// primarily interested in pointer types and enumeration types. We also
6435/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006436/// AllowUserConversions is true if we should look at the conversion
6437/// functions of a class type, and AllowExplicitConversions if we
6438/// should also include the explicit conversion functions of a class
6439/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00006440void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006441BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006442 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006443 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006444 bool AllowExplicitConversions,
6445 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006446 // Only deal with canonical types.
6447 Ty = Context.getCanonicalType(Ty);
6448
6449 // Look through reference types; they aren't part of the type of an
6450 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00006451 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006452 Ty = RefTy->getPointeeType();
6453
John McCall3b657512011-01-19 10:06:00 +00006454 // If we're dealing with an array type, decay to the pointer.
6455 if (Ty->isArrayType())
6456 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6457
6458 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006459 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006460
Chandler Carruth6a577462010-12-13 01:44:01 +00006461 // Flag if we ever add a non-record type.
6462 const RecordType *TyRec = Ty->getAs<RecordType>();
6463 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6464
Chandler Carruth6a577462010-12-13 01:44:01 +00006465 // Flag if we encounter an arithmetic type.
6466 HasArithmeticOrEnumeralTypes =
6467 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6468
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006469 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6470 PointerTypes.insert(Ty);
6471 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006472 // Insert our type, and its more-qualified variants, into the set
6473 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006474 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006475 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00006476 } else if (Ty->isMemberPointerType()) {
6477 // Member pointers are far easier, since the pointee can't be converted.
6478 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6479 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006480 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006481 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00006482 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006483 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006484 // We treat vector types as arithmetic types in many contexts as an
6485 // extension.
6486 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00006487 VectorTypes.insert(Ty);
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006488 } else if (Ty->isNullPtrType()) {
6489 HasNullPtrType = true;
Chandler Carruth6a577462010-12-13 01:44:01 +00006490 } else if (AllowUserConversions && TyRec) {
6491 // No conversion functions in incomplete types.
6492 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6493 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006494
Chandler Carruth6a577462010-12-13 01:44:01 +00006495 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006496 std::pair<CXXRecordDecl::conversion_iterator,
6497 CXXRecordDecl::conversion_iterator>
6498 Conversions = ClassDecl->getVisibleConversionFunctions();
6499 for (CXXRecordDecl::conversion_iterator
6500 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006501 NamedDecl *D = I.getDecl();
6502 if (isa<UsingShadowDecl>(D))
6503 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006504
Chandler Carruth6a577462010-12-13 01:44:01 +00006505 // Skip conversion function templates; they don't tell us anything
6506 // about which builtin types we can convert to.
6507 if (isa<FunctionTemplateDecl>(D))
6508 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006509
Chandler Carruth6a577462010-12-13 01:44:01 +00006510 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6511 if (AllowExplicitConversions || !Conv->isExplicit()) {
6512 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6513 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006514 }
6515 }
6516 }
6517}
6518
Douglas Gregor19b7b152009-08-24 13:43:27 +00006519/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6520/// the volatile- and non-volatile-qualified assignment operators for the
6521/// given type to the candidate set.
6522static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6523 QualType T,
Richard Smith958ba642013-05-05 15:51:06 +00006524 ArrayRef<Expr *> Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006525 OverloadCandidateSet &CandidateSet) {
6526 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00006527
Douglas Gregor19b7b152009-08-24 13:43:27 +00006528 // T& operator=(T&, T)
6529 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6530 ParamTypes[1] = T;
Richard Smith958ba642013-05-05 15:51:06 +00006531 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006532 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00006533
Douglas Gregor19b7b152009-08-24 13:43:27 +00006534 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6535 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00006536 ParamTypes[0]
6537 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00006538 ParamTypes[1] = T;
Richard Smith958ba642013-05-05 15:51:06 +00006539 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00006540 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00006541 }
6542}
Mike Stump1eb44332009-09-09 15:08:12 +00006543
Sebastian Redl9994a342009-10-25 17:03:50 +00006544/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6545/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006546static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6547 Qualifiers VRQuals;
6548 const RecordType *TyRec;
6549 if (const MemberPointerType *RHSMPType =
6550 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00006551 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006552 else
6553 TyRec = ArgExpr->getType()->getAs<RecordType>();
6554 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006555 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006556 VRQuals.addVolatile();
6557 VRQuals.addRestrict();
6558 return VRQuals;
6559 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006560
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006561 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00006562 if (!ClassDecl->hasDefinition())
6563 return VRQuals;
6564
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006565 std::pair<CXXRecordDecl::conversion_iterator,
6566 CXXRecordDecl::conversion_iterator>
6567 Conversions = ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006568
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006569 for (CXXRecordDecl::conversion_iterator
6570 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00006571 NamedDecl *D = I.getDecl();
6572 if (isa<UsingShadowDecl>(D))
6573 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6574 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006575 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6576 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6577 CanTy = ResTypeRef->getPointeeType();
6578 // Need to go down the pointer/mempointer chain and add qualifiers
6579 // as see them.
6580 bool done = false;
6581 while (!done) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006582 if (CanTy.isRestrictQualified())
6583 VRQuals.addRestrict();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006584 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6585 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006586 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006587 CanTy->getAs<MemberPointerType>())
6588 CanTy = ResTypeMPtr->getPointeeType();
6589 else
6590 done = true;
6591 if (CanTy.isVolatileQualified())
6592 VRQuals.addVolatile();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006593 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6594 return VRQuals;
6595 }
6596 }
6597 }
6598 return VRQuals;
6599}
John McCall00071ec2010-11-13 05:51:15 +00006600
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006601namespace {
John McCall00071ec2010-11-13 05:51:15 +00006602
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006603/// \brief Helper class to manage the addition of builtin operator overload
6604/// candidates. It provides shared state and utility methods used throughout
6605/// the process, as well as a helper method to add each group of builtin
6606/// operator overloads from the standard to a candidate set.
6607class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00006608 // Common instance state available to all overload candidate addition methods.
6609 Sema &S;
Richard Smith958ba642013-05-05 15:51:06 +00006610 ArrayRef<Expr *> Args;
Chandler Carruth6d695582010-12-12 10:35:00 +00006611 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00006612 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006613 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruth6d695582010-12-12 10:35:00 +00006614 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006615
Chandler Carruth6d695582010-12-12 10:35:00 +00006616 // Define some constants used to index and iterate over the arithemetic types
6617 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00006618 // The "promoted arithmetic types" are the arithmetic
6619 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00006620 static const unsigned FirstIntegralType = 3;
Richard Smith3c2fcf82012-06-10 08:00:26 +00006621 static const unsigned LastIntegralType = 20;
John McCall00071ec2010-11-13 05:51:15 +00006622 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006623 LastPromotedIntegralType = 11;
John McCall00071ec2010-11-13 05:51:15 +00006624 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006625 LastPromotedArithmeticType = 11;
6626 static const unsigned NumArithmeticTypes = 20;
John McCall00071ec2010-11-13 05:51:15 +00006627
Chandler Carruth6d695582010-12-12 10:35:00 +00006628 /// \brief Get the canonical type for a given arithmetic type index.
6629 CanQualType getArithmeticType(unsigned index) {
6630 assert(index < NumArithmeticTypes);
6631 static CanQualType ASTContext::* const
6632 ArithmeticTypes[NumArithmeticTypes] = {
6633 // Start of promoted types.
6634 &ASTContext::FloatTy,
6635 &ASTContext::DoubleTy,
6636 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00006637
Chandler Carruth6d695582010-12-12 10:35:00 +00006638 // Start of integral types.
6639 &ASTContext::IntTy,
6640 &ASTContext::LongTy,
6641 &ASTContext::LongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006642 &ASTContext::Int128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006643 &ASTContext::UnsignedIntTy,
6644 &ASTContext::UnsignedLongTy,
6645 &ASTContext::UnsignedLongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006646 &ASTContext::UnsignedInt128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006647 // End of promoted types.
6648
6649 &ASTContext::BoolTy,
6650 &ASTContext::CharTy,
6651 &ASTContext::WCharTy,
6652 &ASTContext::Char16Ty,
6653 &ASTContext::Char32Ty,
6654 &ASTContext::SignedCharTy,
6655 &ASTContext::ShortTy,
6656 &ASTContext::UnsignedCharTy,
6657 &ASTContext::UnsignedShortTy,
6658 // End of integral types.
Richard Smith3c2fcf82012-06-10 08:00:26 +00006659 // FIXME: What about complex? What about half?
Chandler Carruth6d695582010-12-12 10:35:00 +00006660 };
6661 return S.Context.*ArithmeticTypes[index];
6662 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006663
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006664 /// \brief Gets the canonical type resulting from the usual arithemetic
6665 /// converions for the given arithmetic types.
6666 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6667 // Accelerator table for performing the usual arithmetic conversions.
6668 // The rules are basically:
6669 // - if either is floating-point, use the wider floating-point
6670 // - if same signedness, use the higher rank
6671 // - if same size, use unsigned of the higher rank
6672 // - use the larger type
6673 // These rules, together with the axiom that higher ranks are
6674 // never smaller, are sufficient to precompute all of these results
6675 // *except* when dealing with signed types of higher rank.
6676 // (we could precompute SLL x UI for all known platforms, but it's
6677 // better not to make any assumptions).
Richard Smith3c2fcf82012-06-10 08:00:26 +00006678 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006679 enum PromotedType {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006680 Dep=-1,
6681 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006682 };
Nuno Lopes79e244f2012-04-21 14:45:25 +00006683 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006684 [LastPromotedArithmeticType] = {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006685/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6686/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6687/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6688/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6689/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6690/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6691/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6692/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6693/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6694/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6695/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006696 };
6697
6698 assert(L < LastPromotedArithmeticType);
6699 assert(R < LastPromotedArithmeticType);
6700 int Idx = ConversionsTable[L][R];
6701
6702 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00006703 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006704
6705 // Slow path: we need to compare widths.
6706 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00006707 CanQualType LT = getArithmeticType(L),
6708 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006709 unsigned LW = S.Context.getIntWidth(LT),
6710 RW = S.Context.getIntWidth(RT);
6711
6712 // If they're different widths, use the signed type.
6713 if (LW > RW) return LT;
6714 else if (LW < RW) return RT;
6715
6716 // Otherwise, use the unsigned type of the signed type's rank.
6717 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6718 assert(L == SLL || R == SLL);
6719 return S.Context.UnsignedLongLongTy;
6720 }
6721
Chandler Carruth3c69dc42010-12-12 09:22:45 +00006722 /// \brief Helper method to factor out the common pattern of adding overloads
6723 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006724 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006725 bool HasVolatile,
6726 bool HasRestrict) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006727 QualType ParamTypes[2] = {
6728 S.Context.getLValueReferenceType(CandidateTy),
6729 S.Context.IntTy
6730 };
6731
6732 // Non-volatile version.
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
6738 // Use a heuristic to reduce number of builtin candidates in the set:
6739 // add volatile version only if there are conversions to a volatile type.
6740 if (HasVolatile) {
6741 ParamTypes[0] =
6742 S.Context.getLValueReferenceType(
6743 S.Context.getVolatileType(CandidateTy));
Richard Smith958ba642013-05-05 15:51:06 +00006744 if (Args.size() == 1)
6745 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006746 else
Richard Smith958ba642013-05-05 15:51:06 +00006747 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006748 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006749
6750 // Add restrict version only if there are conversions to a restrict type
6751 // and our candidate type is a non-restrict-qualified pointer.
6752 if (HasRestrict && CandidateTy->isAnyPointerType() &&
6753 !CandidateTy.isRestrictQualified()) {
6754 ParamTypes[0]
6755 = S.Context.getLValueReferenceType(
6756 S.Context.getCVRQualifiedType(CandidateTy, 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 if (HasVolatile) {
6763 ParamTypes[0]
6764 = S.Context.getLValueReferenceType(
6765 S.Context.getCVRQualifiedType(CandidateTy,
6766 (Qualifiers::Volatile |
6767 Qualifiers::Restrict)));
Richard Smith958ba642013-05-05 15:51:06 +00006768 if (Args.size() == 1)
6769 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006770 else
Richard Smith958ba642013-05-05 15:51:06 +00006771 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006772 }
6773 }
6774
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006775 }
6776
6777public:
6778 BuiltinOperatorOverloadBuilder(
Richard Smith958ba642013-05-05 15:51:06 +00006779 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006780 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00006781 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006782 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006783 OverloadCandidateSet &CandidateSet)
Richard Smith958ba642013-05-05 15:51:06 +00006784 : S(S), Args(Args),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006785 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00006786 HasArithmeticOrEnumeralCandidateType(
6787 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006788 CandidateTypes(CandidateTypes),
6789 CandidateSet(CandidateSet) {
6790 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00006791 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006792 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006793 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006794 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006795 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006796 assert(getArithmeticType(FirstPromotedArithmeticType)
6797 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006798 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006799 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006800 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006801 "Invalid last promoted arithmetic type");
6802 }
6803
6804 // C++ [over.built]p3:
6805 //
6806 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6807 // is either volatile or empty, there exist candidate operator
6808 // functions of the form
6809 //
6810 // VQ T& operator++(VQ T&);
6811 // T operator++(VQ T&, int);
6812 //
6813 // C++ [over.built]p4:
6814 //
6815 // For every pair (T, VQ), where T is an arithmetic type other
6816 // than bool, and VQ is either volatile or empty, there exist
6817 // candidate operator functions of the form
6818 //
6819 // VQ T& operator--(VQ T&);
6820 // T operator--(VQ T&, int);
6821 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006822 if (!HasArithmeticOrEnumeralCandidateType)
6823 return;
6824
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006825 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6826 Arith < NumArithmeticTypes; ++Arith) {
6827 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00006828 getArithmeticType(Arith),
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006829 VisibleTypeConversionsQuals.hasVolatile(),
6830 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006831 }
6832 }
6833
6834 // C++ [over.built]p5:
6835 //
6836 // For every pair (T, VQ), where T is a cv-qualified or
6837 // cv-unqualified object type, and VQ is either volatile or
6838 // empty, there exist candidate operator functions of the form
6839 //
6840 // T*VQ& operator++(T*VQ&);
6841 // T*VQ& operator--(T*VQ&);
6842 // T* operator++(T*VQ&, int);
6843 // T* operator--(T*VQ&, int);
6844 void addPlusPlusMinusMinusPointerOverloads() {
6845 for (BuiltinCandidateTypeSet::iterator
6846 Ptr = CandidateTypes[0].pointer_begin(),
6847 PtrEnd = CandidateTypes[0].pointer_end();
6848 Ptr != PtrEnd; ++Ptr) {
6849 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006850 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006851 continue;
6852
6853 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006854 (!(*Ptr).isVolatileQualified() &&
6855 VisibleTypeConversionsQuals.hasVolatile()),
6856 (!(*Ptr).isRestrictQualified() &&
6857 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006858 }
6859 }
6860
6861 // C++ [over.built]p6:
6862 // For every cv-qualified or cv-unqualified object type T, there
6863 // exist candidate operator functions of the form
6864 //
6865 // T& operator*(T*);
6866 //
6867 // C++ [over.built]p7:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006868 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006869 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006870 // T& operator*(T*);
6871 void addUnaryStarPointerOverloads() {
6872 for (BuiltinCandidateTypeSet::iterator
6873 Ptr = CandidateTypes[0].pointer_begin(),
6874 PtrEnd = CandidateTypes[0].pointer_end();
6875 Ptr != PtrEnd; ++Ptr) {
6876 QualType ParamTy = *Ptr;
6877 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006878 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6879 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006880
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006881 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6882 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6883 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006884
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006885 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smith958ba642013-05-05 15:51:06 +00006886 &ParamTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006887 }
6888 }
6889
6890 // C++ [over.built]p9:
6891 // For every promoted arithmetic type T, there exist candidate
6892 // operator functions of the form
6893 //
6894 // T operator+(T);
6895 // T operator-(T);
6896 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006897 if (!HasArithmeticOrEnumeralCandidateType)
6898 return;
6899
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006900 for (unsigned Arith = FirstPromotedArithmeticType;
6901 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006902 QualType ArithTy = getArithmeticType(Arith);
Richard Smith958ba642013-05-05 15:51:06 +00006903 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006904 }
6905
6906 // Extension: We also add these operators for vector types.
6907 for (BuiltinCandidateTypeSet::iterator
6908 Vec = CandidateTypes[0].vector_begin(),
6909 VecEnd = CandidateTypes[0].vector_end();
6910 Vec != VecEnd; ++Vec) {
6911 QualType VecTy = *Vec;
Richard Smith958ba642013-05-05 15:51:06 +00006912 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006913 }
6914 }
6915
6916 // C++ [over.built]p8:
6917 // For every type T, there exist candidate operator functions of
6918 // the form
6919 //
6920 // T* operator+(T*);
6921 void addUnaryPlusPointerOverloads() {
6922 for (BuiltinCandidateTypeSet::iterator
6923 Ptr = CandidateTypes[0].pointer_begin(),
6924 PtrEnd = CandidateTypes[0].pointer_end();
6925 Ptr != PtrEnd; ++Ptr) {
6926 QualType ParamTy = *Ptr;
Richard Smith958ba642013-05-05 15:51:06 +00006927 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006928 }
6929 }
6930
6931 // C++ [over.built]p10:
6932 // For every promoted integral type T, there exist candidate
6933 // operator functions of the form
6934 //
6935 // T operator~(T);
6936 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006937 if (!HasArithmeticOrEnumeralCandidateType)
6938 return;
6939
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006940 for (unsigned Int = FirstPromotedIntegralType;
6941 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006942 QualType IntTy = getArithmeticType(Int);
Richard Smith958ba642013-05-05 15:51:06 +00006943 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006944 }
6945
6946 // Extension: We also add this operator for vector types.
6947 for (BuiltinCandidateTypeSet::iterator
6948 Vec = CandidateTypes[0].vector_begin(),
6949 VecEnd = CandidateTypes[0].vector_end();
6950 Vec != VecEnd; ++Vec) {
6951 QualType VecTy = *Vec;
Richard Smith958ba642013-05-05 15:51:06 +00006952 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006953 }
6954 }
6955
6956 // C++ [over.match.oper]p16:
6957 // For every pointer to member type T, there exist candidate operator
6958 // functions of the form
6959 //
6960 // bool operator==(T,T);
6961 // bool operator!=(T,T);
6962 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6963 /// Set of (canonical) types that we've already handled.
6964 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6965
Richard Smith958ba642013-05-05 15:51:06 +00006966 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006967 for (BuiltinCandidateTypeSet::iterator
6968 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6969 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6970 MemPtr != MemPtrEnd;
6971 ++MemPtr) {
6972 // Don't add the same builtin candidate twice.
6973 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6974 continue;
6975
6976 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smith958ba642013-05-05 15:51:06 +00006977 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006978 }
6979 }
6980 }
6981
6982 // C++ [over.built]p15:
6983 //
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006984 // For every T, where T is an enumeration type, a pointer type, or
6985 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006986 //
6987 // bool operator<(T, T);
6988 // bool operator>(T, T);
6989 // bool operator<=(T, T);
6990 // bool operator>=(T, T);
6991 // bool operator==(T, T);
6992 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006993 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman97c67392012-09-18 21:52:24 +00006994 // C++ [over.match.oper]p3:
6995 // [...]the built-in candidates include all of the candidate operator
6996 // functions defined in 13.6 that, compared to the given operator, [...]
6997 // do not have the same parameter-type-list as any non-template non-member
6998 // candidate.
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006999 //
Eli Friedman97c67392012-09-18 21:52:24 +00007000 // Note that in practice, this only affects enumeration types because there
7001 // aren't any built-in candidates of record type, and a user-defined operator
7002 // must have an operand of record or enumeration type. Also, the only other
7003 // overloaded operator with enumeration arguments, operator=,
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007004 // cannot be overloaded for enumeration types, so this is the only place
7005 // where we must suppress candidates like this.
7006 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7007 UserDefinedBinaryOperators;
7008
Richard Smith958ba642013-05-05 15:51:06 +00007009 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007010 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7011 CandidateTypes[ArgIdx].enumeration_end()) {
7012 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7013 CEnd = CandidateSet.end();
7014 C != CEnd; ++C) {
7015 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7016 continue;
7017
Eli Friedman97c67392012-09-18 21:52:24 +00007018 if (C->Function->isFunctionTemplateSpecialization())
7019 continue;
7020
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007021 QualType FirstParamType =
7022 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7023 QualType SecondParamType =
7024 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7025
7026 // Skip if either parameter isn't of enumeral type.
7027 if (!FirstParamType->isEnumeralType() ||
7028 !SecondParamType->isEnumeralType())
7029 continue;
7030
7031 // Add this operator to the set of known user-defined operators.
7032 UserDefinedBinaryOperators.insert(
7033 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7034 S.Context.getCanonicalType(SecondParamType)));
7035 }
7036 }
7037 }
7038
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007039 /// Set of (canonical) types that we've already handled.
7040 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7041
Richard Smith958ba642013-05-05 15:51:06 +00007042 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007043 for (BuiltinCandidateTypeSet::iterator
7044 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7045 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7046 Ptr != PtrEnd; ++Ptr) {
7047 // Don't add the same builtin candidate twice.
7048 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7049 continue;
7050
7051 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smith958ba642013-05-05 15:51:06 +00007052 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007053 }
7054 for (BuiltinCandidateTypeSet::iterator
7055 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7056 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7057 Enum != EnumEnd; ++Enum) {
7058 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7059
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007060 // Don't add the same builtin candidate twice, or if a user defined
7061 // candidate exists.
7062 if (!AddedTypes.insert(CanonType) ||
7063 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7064 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007065 continue;
7066
7067 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smith958ba642013-05-05 15:51:06 +00007068 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007069 }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00007070
7071 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7072 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7073 if (AddedTypes.insert(NullPtrTy) &&
Richard Smith958ba642013-05-05 15:51:06 +00007074 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00007075 NullPtrTy))) {
7076 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smith958ba642013-05-05 15:51:06 +00007077 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00007078 CandidateSet);
7079 }
7080 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007081 }
7082 }
7083
7084 // C++ [over.built]p13:
7085 //
7086 // For every cv-qualified or cv-unqualified object type T
7087 // there exist candidate operator functions of the form
7088 //
7089 // T* operator+(T*, ptrdiff_t);
7090 // T& operator[](T*, ptrdiff_t); [BELOW]
7091 // T* operator-(T*, ptrdiff_t);
7092 // T* operator+(ptrdiff_t, T*);
7093 // T& operator[](ptrdiff_t, T*); [BELOW]
7094 //
7095 // C++ [over.built]p14:
7096 //
7097 // For every T, where T is a pointer to object type, there
7098 // exist candidate operator functions of the form
7099 //
7100 // ptrdiff_t operator-(T, T);
7101 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7102 /// Set of (canonical) types that we've already handled.
7103 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7104
7105 for (int Arg = 0; Arg < 2; ++Arg) {
7106 QualType AsymetricParamTypes[2] = {
7107 S.Context.getPointerDiffType(),
7108 S.Context.getPointerDiffType(),
7109 };
7110 for (BuiltinCandidateTypeSet::iterator
7111 Ptr = CandidateTypes[Arg].pointer_begin(),
7112 PtrEnd = CandidateTypes[Arg].pointer_end();
7113 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007114 QualType PointeeTy = (*Ptr)->getPointeeType();
7115 if (!PointeeTy->isObjectType())
7116 continue;
7117
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007118 AsymetricParamTypes[Arg] = *Ptr;
7119 if (Arg == 0 || Op == OO_Plus) {
7120 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7121 // T* operator+(ptrdiff_t, T*);
Richard Smith958ba642013-05-05 15:51:06 +00007122 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007123 }
7124 if (Op == OO_Minus) {
7125 // ptrdiff_t operator-(T, T);
7126 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7127 continue;
7128
7129 QualType ParamTypes[2] = { *Ptr, *Ptr };
7130 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smith958ba642013-05-05 15:51:06 +00007131 Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007132 }
7133 }
7134 }
7135 }
7136
7137 // C++ [over.built]p12:
7138 //
7139 // For every pair of promoted arithmetic types L and R, there
7140 // exist candidate operator functions of the form
7141 //
7142 // LR operator*(L, R);
7143 // LR operator/(L, R);
7144 // LR operator+(L, R);
7145 // LR operator-(L, R);
7146 // bool operator<(L, R);
7147 // bool operator>(L, R);
7148 // bool operator<=(L, R);
7149 // bool operator>=(L, R);
7150 // bool operator==(L, R);
7151 // bool operator!=(L, R);
7152 //
7153 // where LR is the result of the usual arithmetic conversions
7154 // between types L and R.
7155 //
7156 // C++ [over.built]p24:
7157 //
7158 // For every pair of promoted arithmetic types L and R, there exist
7159 // candidate operator functions of the form
7160 //
7161 // LR operator?(bool, L, R);
7162 //
7163 // where LR is the result of the usual arithmetic conversions
7164 // between types L and R.
7165 // Our candidates ignore the first parameter.
7166 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007167 if (!HasArithmeticOrEnumeralCandidateType)
7168 return;
7169
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007170 for (unsigned Left = FirstPromotedArithmeticType;
7171 Left < LastPromotedArithmeticType; ++Left) {
7172 for (unsigned Right = FirstPromotedArithmeticType;
7173 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007174 QualType LandR[2] = { getArithmeticType(Left),
7175 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007176 QualType Result =
7177 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007178 : getUsualArithmeticConversions(Left, Right);
Richard Smith958ba642013-05-05 15:51:06 +00007179 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007180 }
7181 }
7182
7183 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7184 // conditional operator for vector types.
7185 for (BuiltinCandidateTypeSet::iterator
7186 Vec1 = CandidateTypes[0].vector_begin(),
7187 Vec1End = CandidateTypes[0].vector_end();
7188 Vec1 != Vec1End; ++Vec1) {
7189 for (BuiltinCandidateTypeSet::iterator
7190 Vec2 = CandidateTypes[1].vector_begin(),
7191 Vec2End = CandidateTypes[1].vector_end();
7192 Vec2 != Vec2End; ++Vec2) {
7193 QualType LandR[2] = { *Vec1, *Vec2 };
7194 QualType Result = S.Context.BoolTy;
7195 if (!isComparison) {
7196 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7197 Result = *Vec1;
7198 else
7199 Result = *Vec2;
7200 }
7201
Richard Smith958ba642013-05-05 15:51:06 +00007202 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007203 }
7204 }
7205 }
7206
7207 // C++ [over.built]p17:
7208 //
7209 // For every pair of promoted integral types L and R, there
7210 // exist candidate operator functions of the form
7211 //
7212 // LR operator%(L, R);
7213 // LR operator&(L, R);
7214 // LR operator^(L, R);
7215 // LR operator|(L, R);
7216 // L operator<<(L, R);
7217 // L operator>>(L, R);
7218 //
7219 // where LR is the result of the usual arithmetic conversions
7220 // between types L and R.
7221 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007222 if (!HasArithmeticOrEnumeralCandidateType)
7223 return;
7224
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007225 for (unsigned Left = FirstPromotedIntegralType;
7226 Left < LastPromotedIntegralType; ++Left) {
7227 for (unsigned Right = FirstPromotedIntegralType;
7228 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007229 QualType LandR[2] = { getArithmeticType(Left),
7230 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007231 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7232 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007233 : getUsualArithmeticConversions(Left, Right);
Richard Smith958ba642013-05-05 15:51:06 +00007234 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007235 }
7236 }
7237 }
7238
7239 // C++ [over.built]p20:
7240 //
7241 // For every pair (T, VQ), where T is an enumeration or
7242 // pointer to member type and VQ is either volatile or
7243 // empty, there exist candidate operator functions of the form
7244 //
7245 // VQ T& operator=(VQ T&, T);
7246 void addAssignmentMemberPointerOrEnumeralOverloads() {
7247 /// Set of (canonical) types that we've already handled.
7248 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7249
7250 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7251 for (BuiltinCandidateTypeSet::iterator
7252 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7253 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7254 Enum != EnumEnd; ++Enum) {
7255 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7256 continue;
7257
Richard Smith958ba642013-05-05 15:51:06 +00007258 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007259 }
7260
7261 for (BuiltinCandidateTypeSet::iterator
7262 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7263 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7264 MemPtr != MemPtrEnd; ++MemPtr) {
7265 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7266 continue;
7267
Richard Smith958ba642013-05-05 15:51:06 +00007268 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007269 }
7270 }
7271 }
7272
7273 // C++ [over.built]p19:
7274 //
7275 // For every pair (T, VQ), where T is any type and VQ is either
7276 // volatile or empty, there exist candidate operator functions
7277 // of the form
7278 //
7279 // T*VQ& operator=(T*VQ&, T*);
7280 //
7281 // C++ [over.built]p21:
7282 //
7283 // For every pair (T, VQ), where T is a cv-qualified or
7284 // cv-unqualified object type and VQ is either volatile or
7285 // empty, there exist candidate operator functions of the form
7286 //
7287 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7288 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7289 void addAssignmentPointerOverloads(bool isEqualOp) {
7290 /// Set of (canonical) types that we've already handled.
7291 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7292
7293 for (BuiltinCandidateTypeSet::iterator
7294 Ptr = CandidateTypes[0].pointer_begin(),
7295 PtrEnd = CandidateTypes[0].pointer_end();
7296 Ptr != PtrEnd; ++Ptr) {
7297 // If this is operator=, keep track of the builtin candidates we added.
7298 if (isEqualOp)
7299 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007300 else if (!(*Ptr)->getPointeeType()->isObjectType())
7301 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007302
7303 // non-volatile version
7304 QualType ParamTypes[2] = {
7305 S.Context.getLValueReferenceType(*Ptr),
7306 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7307 };
Richard Smith958ba642013-05-05 15:51:06 +00007308 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007309 /*IsAssigmentOperator=*/ isEqualOp);
7310
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007311 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7312 VisibleTypeConversionsQuals.hasVolatile();
7313 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007314 // volatile version
7315 ParamTypes[0] =
7316 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007317 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007318 /*IsAssigmentOperator=*/isEqualOp);
7319 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007320
7321 if (!(*Ptr).isRestrictQualified() &&
7322 VisibleTypeConversionsQuals.hasRestrict()) {
7323 // restrict version
7324 ParamTypes[0]
7325 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007326 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007327 /*IsAssigmentOperator=*/isEqualOp);
7328
7329 if (NeedVolatile) {
7330 // volatile restrict version
7331 ParamTypes[0]
7332 = S.Context.getLValueReferenceType(
7333 S.Context.getCVRQualifiedType(*Ptr,
7334 (Qualifiers::Volatile |
7335 Qualifiers::Restrict)));
Richard Smith958ba642013-05-05 15:51:06 +00007336 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007337 /*IsAssigmentOperator=*/isEqualOp);
7338 }
7339 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007340 }
7341
7342 if (isEqualOp) {
7343 for (BuiltinCandidateTypeSet::iterator
7344 Ptr = CandidateTypes[1].pointer_begin(),
7345 PtrEnd = CandidateTypes[1].pointer_end();
7346 Ptr != PtrEnd; ++Ptr) {
7347 // Make sure we don't add the same candidate twice.
7348 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7349 continue;
7350
Chandler Carruth6df868e2010-12-12 08:17:55 +00007351 QualType ParamTypes[2] = {
7352 S.Context.getLValueReferenceType(*Ptr),
7353 *Ptr,
7354 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007355
7356 // non-volatile version
Richard Smith958ba642013-05-05 15:51:06 +00007357 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007358 /*IsAssigmentOperator=*/true);
7359
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007360 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7361 VisibleTypeConversionsQuals.hasVolatile();
7362 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007363 // volatile version
7364 ParamTypes[0] =
7365 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007366 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7367 /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007368 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007369
7370 if (!(*Ptr).isRestrictQualified() &&
7371 VisibleTypeConversionsQuals.hasRestrict()) {
7372 // restrict version
7373 ParamTypes[0]
7374 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007375 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7376 /*IsAssigmentOperator=*/true);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007377
7378 if (NeedVolatile) {
7379 // volatile restrict version
7380 ParamTypes[0]
7381 = S.Context.getLValueReferenceType(
7382 S.Context.getCVRQualifiedType(*Ptr,
7383 (Qualifiers::Volatile |
7384 Qualifiers::Restrict)));
Richard Smith958ba642013-05-05 15:51:06 +00007385 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7386 /*IsAssigmentOperator=*/true);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007387 }
7388 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007389 }
7390 }
7391 }
7392
7393 // C++ [over.built]p18:
7394 //
7395 // For every triple (L, VQ, R), where L is an arithmetic type,
7396 // VQ is either volatile or empty, and R is a promoted
7397 // arithmetic type, there exist candidate operator functions of
7398 // the form
7399 //
7400 // VQ L& operator=(VQ L&, R);
7401 // VQ L& operator*=(VQ L&, R);
7402 // VQ L& operator/=(VQ L&, R);
7403 // VQ L& operator+=(VQ L&, R);
7404 // VQ L& operator-=(VQ L&, R);
7405 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007406 if (!HasArithmeticOrEnumeralCandidateType)
7407 return;
7408
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007409 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7410 for (unsigned Right = FirstPromotedArithmeticType;
7411 Right < LastPromotedArithmeticType; ++Right) {
7412 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007413 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007414
7415 // Add this built-in operator as a candidate (VQ is empty).
7416 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007417 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smith958ba642013-05-05 15:51:06 +00007418 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007419 /*IsAssigmentOperator=*/isEqualOp);
7420
7421 // Add this built-in operator as a candidate (VQ is 'volatile').
7422 if (VisibleTypeConversionsQuals.hasVolatile()) {
7423 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007424 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007425 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smith958ba642013-05-05 15:51:06 +00007426 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007427 /*IsAssigmentOperator=*/isEqualOp);
7428 }
7429 }
7430 }
7431
7432 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7433 for (BuiltinCandidateTypeSet::iterator
7434 Vec1 = CandidateTypes[0].vector_begin(),
7435 Vec1End = CandidateTypes[0].vector_end();
7436 Vec1 != Vec1End; ++Vec1) {
7437 for (BuiltinCandidateTypeSet::iterator
7438 Vec2 = CandidateTypes[1].vector_begin(),
7439 Vec2End = CandidateTypes[1].vector_end();
7440 Vec2 != Vec2End; ++Vec2) {
7441 QualType ParamTypes[2];
7442 ParamTypes[1] = *Vec2;
7443 // Add this built-in operator as a candidate (VQ is empty).
7444 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smith958ba642013-05-05 15:51:06 +00007445 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007446 /*IsAssigmentOperator=*/isEqualOp);
7447
7448 // Add this built-in operator as a candidate (VQ is 'volatile').
7449 if (VisibleTypeConversionsQuals.hasVolatile()) {
7450 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7451 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smith958ba642013-05-05 15:51:06 +00007452 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007453 /*IsAssigmentOperator=*/isEqualOp);
7454 }
7455 }
7456 }
7457 }
7458
7459 // C++ [over.built]p22:
7460 //
7461 // For every triple (L, VQ, R), where L is an integral type, VQ
7462 // is either volatile or empty, and R is a promoted integral
7463 // type, there exist candidate operator functions of the form
7464 //
7465 // VQ L& operator%=(VQ L&, R);
7466 // VQ L& operator<<=(VQ L&, R);
7467 // VQ L& operator>>=(VQ L&, R);
7468 // VQ L& operator&=(VQ L&, R);
7469 // VQ L& operator^=(VQ L&, R);
7470 // VQ L& operator|=(VQ L&, R);
7471 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00007472 if (!HasArithmeticOrEnumeralCandidateType)
7473 return;
7474
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007475 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7476 for (unsigned Right = FirstPromotedIntegralType;
7477 Right < LastPromotedIntegralType; ++Right) {
7478 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007479 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007480
7481 // Add this built-in operator as a candidate (VQ is empty).
7482 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007483 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smith958ba642013-05-05 15:51:06 +00007484 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007485 if (VisibleTypeConversionsQuals.hasVolatile()) {
7486 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00007487 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007488 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7489 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smith958ba642013-05-05 15:51:06 +00007490 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007491 }
7492 }
7493 }
7494 }
7495
7496 // C++ [over.operator]p23:
7497 //
7498 // There also exist candidate operator functions of the form
7499 //
7500 // bool operator!(bool);
7501 // bool operator&&(bool, bool);
7502 // bool operator||(bool, bool);
7503 void addExclaimOverload() {
7504 QualType ParamTy = S.Context.BoolTy;
Richard Smith958ba642013-05-05 15:51:06 +00007505 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007506 /*IsAssignmentOperator=*/false,
7507 /*NumContextualBoolArguments=*/1);
7508 }
7509 void addAmpAmpOrPipePipeOverload() {
7510 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smith958ba642013-05-05 15:51:06 +00007511 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007512 /*IsAssignmentOperator=*/false,
7513 /*NumContextualBoolArguments=*/2);
7514 }
7515
7516 // C++ [over.built]p13:
7517 //
7518 // For every cv-qualified or cv-unqualified object type T there
7519 // exist candidate operator functions of the form
7520 //
7521 // T* operator+(T*, ptrdiff_t); [ABOVE]
7522 // T& operator[](T*, ptrdiff_t);
7523 // T* operator-(T*, ptrdiff_t); [ABOVE]
7524 // T* operator+(ptrdiff_t, T*); [ABOVE]
7525 // T& operator[](ptrdiff_t, T*);
7526 void addSubscriptOverloads() {
7527 for (BuiltinCandidateTypeSet::iterator
7528 Ptr = CandidateTypes[0].pointer_begin(),
7529 PtrEnd = CandidateTypes[0].pointer_end();
7530 Ptr != PtrEnd; ++Ptr) {
7531 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7532 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007533 if (!PointeeType->isObjectType())
7534 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007535
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007536 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7537
7538 // T& operator[](T*, ptrdiff_t)
Richard Smith958ba642013-05-05 15:51:06 +00007539 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007540 }
7541
7542 for (BuiltinCandidateTypeSet::iterator
7543 Ptr = CandidateTypes[1].pointer_begin(),
7544 PtrEnd = CandidateTypes[1].pointer_end();
7545 Ptr != PtrEnd; ++Ptr) {
7546 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7547 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007548 if (!PointeeType->isObjectType())
7549 continue;
7550
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007551 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7552
7553 // T& operator[](ptrdiff_t, T*)
Richard Smith958ba642013-05-05 15:51:06 +00007554 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007555 }
7556 }
7557
7558 // C++ [over.built]p11:
7559 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7560 // C1 is the same type as C2 or is a derived class of C2, T is an object
7561 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7562 // there exist candidate operator functions of the form
7563 //
7564 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7565 //
7566 // where CV12 is the union of CV1 and CV2.
7567 void addArrowStarOverloads() {
7568 for (BuiltinCandidateTypeSet::iterator
7569 Ptr = CandidateTypes[0].pointer_begin(),
7570 PtrEnd = CandidateTypes[0].pointer_end();
7571 Ptr != PtrEnd; ++Ptr) {
7572 QualType C1Ty = (*Ptr);
7573 QualType C1;
7574 QualifierCollector Q1;
7575 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7576 if (!isa<RecordType>(C1))
7577 continue;
7578 // heuristic to reduce number of builtin candidates in the set.
7579 // Add volatile/restrict version only if there are conversions to a
7580 // volatile/restrict type.
7581 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7582 continue;
7583 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7584 continue;
7585 for (BuiltinCandidateTypeSet::iterator
7586 MemPtr = CandidateTypes[1].member_pointer_begin(),
7587 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7588 MemPtr != MemPtrEnd; ++MemPtr) {
7589 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7590 QualType C2 = QualType(mptr->getClass(), 0);
7591 C2 = C2.getUnqualifiedType();
7592 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7593 break;
7594 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7595 // build CV12 T&
7596 QualType T = mptr->getPointeeType();
7597 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7598 T.isVolatileQualified())
7599 continue;
7600 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7601 T.isRestrictQualified())
7602 continue;
7603 T = Q1.apply(S.Context, T);
7604 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smith958ba642013-05-05 15:51:06 +00007605 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007606 }
7607 }
7608 }
7609
7610 // Note that we don't consider the first argument, since it has been
7611 // contextually converted to bool long ago. The candidates below are
7612 // therefore added as binary.
7613 //
7614 // C++ [over.built]p25:
7615 // For every type T, where T is a pointer, pointer-to-member, or scoped
7616 // enumeration type, there exist candidate operator functions of the form
7617 //
7618 // T operator?(bool, T, T);
7619 //
7620 void addConditionalOperatorOverloads() {
7621 /// Set of (canonical) types that we've already handled.
7622 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7623
7624 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7625 for (BuiltinCandidateTypeSet::iterator
7626 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7627 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7628 Ptr != PtrEnd; ++Ptr) {
7629 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7630 continue;
7631
7632 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smith958ba642013-05-05 15:51:06 +00007633 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007634 }
7635
7636 for (BuiltinCandidateTypeSet::iterator
7637 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7638 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7639 MemPtr != MemPtrEnd; ++MemPtr) {
7640 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7641 continue;
7642
7643 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smith958ba642013-05-05 15:51:06 +00007644 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007645 }
7646
Richard Smith80ad52f2013-01-02 11:42:31 +00007647 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007648 for (BuiltinCandidateTypeSet::iterator
7649 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7650 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7651 Enum != EnumEnd; ++Enum) {
7652 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7653 continue;
7654
7655 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7656 continue;
7657
7658 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smith958ba642013-05-05 15:51:06 +00007659 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007660 }
7661 }
7662 }
7663 }
7664};
7665
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007666} // end anonymous namespace
7667
7668/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7669/// operator overloads to the candidate set (C++ [over.built]), based
7670/// on the operator @p Op and the arguments given. For example, if the
7671/// operator is a binary '+', this routine might add "int
7672/// operator+(int, int)" to cover integer addition.
Robert Wilhelm834c0582013-08-09 18:02:13 +00007673void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7674 SourceLocation OpLoc,
7675 ArrayRef<Expr *> Args,
7676 OverloadCandidateSet &CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007677 // Find all of the types that the arguments can convert to, but only
7678 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00007679 // that make use of these types. Also record whether we encounter non-record
7680 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00007681 Qualifiers VisibleTypeConversionsQuals;
7682 VisibleTypeConversionsQuals.addConst();
Richard Smith958ba642013-05-05 15:51:06 +00007683 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanian8621d012009-10-19 21:30:45 +00007684 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00007685
7686 bool HasNonRecordCandidateType = false;
7687 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00007688 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smith958ba642013-05-05 15:51:06 +00007689 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorfec56e72010-11-03 17:00:07 +00007690 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7691 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7692 OpLoc,
7693 true,
7694 (Op == OO_Exclaim ||
7695 Op == OO_AmpAmp ||
7696 Op == OO_PipePipe),
7697 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00007698 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7699 CandidateTypes[ArgIdx].hasNonRecordTypes();
7700 HasArithmeticOrEnumeralCandidateType =
7701 HasArithmeticOrEnumeralCandidateType ||
7702 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00007703 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007704
Chandler Carruth6a577462010-12-13 01:44:01 +00007705 // Exit early when no non-record types have been added to the candidate set
7706 // for any of the arguments to the operator.
Douglas Gregor25aaff92011-10-10 14:05:31 +00007707 //
7708 // We can't exit early for !, ||, or &&, since there we have always have
7709 // 'bool' overloads.
Richard Smith958ba642013-05-05 15:51:06 +00007710 if (!HasNonRecordCandidateType &&
Douglas Gregor25aaff92011-10-10 14:05:31 +00007711 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth6a577462010-12-13 01:44:01 +00007712 return;
7713
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007714 // Setup an object to manage the common state for building overloads.
Richard Smith958ba642013-05-05 15:51:06 +00007715 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007716 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00007717 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007718 CandidateTypes, CandidateSet);
7719
7720 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007721 switch (Op) {
7722 case OO_None:
7723 case NUM_OVERLOADED_OPERATORS:
David Blaikieb219cfc2011-09-23 05:06:16 +00007724 llvm_unreachable("Expected an overloaded operator");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007725
Chandler Carruthabb71842010-12-12 08:51:33 +00007726 case OO_New:
7727 case OO_Delete:
7728 case OO_Array_New:
7729 case OO_Array_Delete:
7730 case OO_Call:
David Blaikieb219cfc2011-09-23 05:06:16 +00007731 llvm_unreachable(
7732 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruthabb71842010-12-12 08:51:33 +00007733
7734 case OO_Comma:
7735 case OO_Arrow:
7736 // C++ [over.match.oper]p3:
7737 // -- For the operator ',', the unary operator '&', or the
7738 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00007739 break;
7740
7741 case OO_Plus: // '+' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007742 if (Args.size() == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007743 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007744 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00007745
7746 case OO_Minus: // '-' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007747 if (Args.size() == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007748 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007749 } else {
7750 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7751 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7752 }
Douglas Gregor74253732008-11-19 15:42:04 +00007753 break;
7754
Chandler Carruthabb71842010-12-12 08:51:33 +00007755 case OO_Star: // '*' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007756 if (Args.size() == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007757 OpBuilder.addUnaryStarPointerOverloads();
7758 else
7759 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7760 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007761
Chandler Carruthabb71842010-12-12 08:51:33 +00007762 case OO_Slash:
7763 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00007764 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007765
7766 case OO_PlusPlus:
7767 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007768 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7769 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00007770 break;
7771
Douglas Gregor19b7b152009-08-24 13:43:27 +00007772 case OO_EqualEqual:
7773 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007774 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007775 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00007776
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007777 case OO_Less:
7778 case OO_Greater:
7779 case OO_LessEqual:
7780 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007781 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007782 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7783 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007784
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007785 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007786 case OO_Caret:
7787 case OO_Pipe:
7788 case OO_LessLess:
7789 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007790 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007791 break;
7792
Chandler Carruthabb71842010-12-12 08:51:33 +00007793 case OO_Amp: // '&' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007794 if (Args.size() == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007795 // C++ [over.match.oper]p3:
7796 // -- For the operator ',', the unary operator '&', or the
7797 // operator '->', the built-in candidates set is empty.
7798 break;
7799
7800 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7801 break;
7802
7803 case OO_Tilde:
7804 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7805 break;
7806
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007807 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007808 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00007809 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007810
7811 case OO_PlusEqual:
7812 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007813 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007814 // Fall through.
7815
7816 case OO_StarEqual:
7817 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007818 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007819 break;
7820
7821 case OO_PercentEqual:
7822 case OO_LessLessEqual:
7823 case OO_GreaterGreaterEqual:
7824 case OO_AmpEqual:
7825 case OO_CaretEqual:
7826 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007827 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007828 break;
7829
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007830 case OO_Exclaim:
7831 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00007832 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007833
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007834 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007835 case OO_PipePipe:
7836 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007837 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007838
7839 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007840 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007841 break;
7842
7843 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007844 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007845 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007846
7847 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007848 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007849 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7850 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007851 }
7852}
7853
Douglas Gregorfa047642009-02-04 00:32:51 +00007854/// \brief Add function candidates found via argument-dependent lookup
7855/// to the set of overloading candidates.
7856///
7857/// This routine performs argument-dependent name lookup based on the
7858/// given function name (which may also be an operator name) and adds
7859/// all of the overload candidates found by ADL to the overload
7860/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00007861void
Douglas Gregorfa047642009-02-04 00:32:51 +00007862Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00007863 bool Operator, SourceLocation Loc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00007864 ArrayRef<Expr *> Args,
Douglas Gregor67714232011-03-03 02:41:12 +00007865 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007866 OverloadCandidateSet& CandidateSet,
Richard Smithb1502bc2012-10-18 17:56:02 +00007867 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00007868 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00007869
John McCalla113e722010-01-26 06:04:06 +00007870 // FIXME: This approach for uniquing ADL results (and removing
7871 // redundant candidates from the set) relies on pointer-equality,
7872 // which means we need to key off the canonical decl. However,
7873 // always going back to the canonical decl might not get us the
7874 // right set of default arguments. What default arguments are
7875 // we supposed to consider on ADL candidates, anyway?
7876
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007877 // FIXME: Pass in the explicit template arguments?
Richard Smithb1502bc2012-10-18 17:56:02 +00007878 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00007879
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007880 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007881 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7882 CandEnd = CandidateSet.end();
7883 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00007884 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00007885 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00007886 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00007887 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00007888 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007889
7890 // For each of the ADL candidates we found, add it to the overload
7891 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00007892 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00007893 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00007894 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00007895 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007896 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007897
Ahmed Charles13a140c2012-02-25 11:00:22 +00007898 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7899 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007900 } else
John McCall6e266892010-01-26 03:27:55 +00007901 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00007902 FoundDecl, ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00007903 Args, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00007904 }
Douglas Gregorfa047642009-02-04 00:32:51 +00007905}
7906
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007907/// isBetterOverloadCandidate - Determines whether the first overload
7908/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00007909bool
John McCall120d63c2010-08-24 20:38:10 +00007910isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00007911 const OverloadCandidate &Cand1,
7912 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007913 SourceLocation Loc,
7914 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007915 // Define viable functions to be better candidates than non-viable
7916 // functions.
7917 if (!Cand2.Viable)
7918 return Cand1.Viable;
7919 else if (!Cand1.Viable)
7920 return false;
7921
Douglas Gregor88a35142008-12-22 05:46:06 +00007922 // C++ [over.match.best]p1:
7923 //
7924 // -- if F is a static member function, ICS1(F) is defined such
7925 // that ICS1(F) is neither better nor worse than ICS1(G) for
7926 // any function G, and, symmetrically, ICS1(G) is neither
7927 // better nor worse than ICS1(F).
7928 unsigned StartArg = 0;
7929 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7930 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007931
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007932 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00007933 // A viable function F1 is defined to be a better function than another
7934 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007935 // conversion sequence than ICSi(F2), and then...
Benjamin Kramer09dd3792012-01-14 16:32:05 +00007936 unsigned NumArgs = Cand1.NumConversions;
7937 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007938 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00007939 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00007940 switch (CompareImplicitConversionSequences(S,
7941 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007942 Cand2.Conversions[ArgIdx])) {
7943 case ImplicitConversionSequence::Better:
7944 // Cand1 has a better conversion sequence.
7945 HasBetterConversion = true;
7946 break;
7947
7948 case ImplicitConversionSequence::Worse:
7949 // Cand1 can't be better than Cand2.
7950 return false;
7951
7952 case ImplicitConversionSequence::Indistinguishable:
7953 // Do nothing.
7954 break;
7955 }
7956 }
7957
Mike Stump1eb44332009-09-09 15:08:12 +00007958 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007959 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007960 if (HasBetterConversion)
7961 return true;
7962
Mike Stump1eb44332009-09-09 15:08:12 +00007963 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007964 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00007965 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007966 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7967 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00007968
7969 // -- F1 and F2 are function template specializations, and the function
7970 // template for F1 is more specialized than the template for F2
7971 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007972 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00007973 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregordfc331e2011-01-19 23:54:39 +00007974 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007975 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00007976 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7977 Cand2.Function->getPrimaryTemplate(),
7978 Loc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007979 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00007980 : TPOC_Call,
Richard Smith66118c22013-09-11 00:52:39 +00007981 Cand1.ExplicitCallArguments,
7982 Cand2.ExplicitCallArguments))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007983 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregordfc331e2011-01-19 23:54:39 +00007984 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007985
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007986 // -- the context is an initialization by user-defined conversion
7987 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7988 // from the return type of F1 to the destination type (i.e.,
7989 // the type of the entity being initialized) is a better
7990 // conversion sequence than the standard conversion sequence
7991 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007992 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00007993 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007994 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregorb734e242012-02-22 17:32:19 +00007995 // First check whether we prefer one of the conversion functions over the
7996 // other. This only distinguishes the results in non-standard, extension
7997 // cases such as the conversion from a lambda closure type to a function
7998 // pointer or block.
7999 ImplicitConversionSequence::CompareKind FuncResult
8000 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8001 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
8002 return FuncResult;
8003
John McCall120d63c2010-08-24 20:38:10 +00008004 switch (CompareStandardConversionSequences(S,
8005 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00008006 Cand2.FinalConversion)) {
8007 case ImplicitConversionSequence::Better:
8008 // Cand1 has a better conversion sequence.
8009 return true;
8010
8011 case ImplicitConversionSequence::Worse:
8012 // Cand1 can't be better than Cand2.
8013 return false;
8014
8015 case ImplicitConversionSequence::Indistinguishable:
8016 // Do nothing
8017 break;
8018 }
8019 }
8020
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008021 return false;
8022}
8023
Mike Stump1eb44332009-09-09 15:08:12 +00008024/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00008025/// within an overload candidate set.
8026///
James Dennettefce31f2012-06-22 08:10:18 +00008027/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregore0762c92009-06-19 23:52:42 +00008028/// which overload resolution occurs.
8029///
James Dennettefce31f2012-06-22 08:10:18 +00008030/// \param Best If overload resolution was successful or found a deleted
8031/// function, \p Best points to the candidate function found.
Douglas Gregore0762c92009-06-19 23:52:42 +00008032///
8033/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00008034OverloadingResult
8035OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00008036 iterator &Best,
Chandler Carruth25ca4212011-02-25 19:41:05 +00008037 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008038 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00008039 Best = end();
8040 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8041 if (Cand->Viable)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008042 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00008043 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008044 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008045 }
8046
8047 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00008048 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008049 return OR_No_Viable_Function;
8050
8051 // Make sure that this function is better than every other viable
8052 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00008053 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00008054 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008055 Cand != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008056 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00008057 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00008058 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008059 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008060 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008061 }
Mike Stump1eb44332009-09-09 15:08:12 +00008062
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008063 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008064 if (Best->Function &&
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008065 (Best->Function->isDeleted() ||
8066 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008067 return OR_Deleted;
8068
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008069 return OR_Success;
8070}
8071
John McCall3c80f572010-01-12 02:15:36 +00008072namespace {
8073
8074enum OverloadCandidateKind {
8075 oc_function,
8076 oc_method,
8077 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00008078 oc_function_template,
8079 oc_method_template,
8080 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00008081 oc_implicit_default_constructor,
8082 oc_implicit_copy_constructor,
Sean Hunt82713172011-05-25 23:16:36 +00008083 oc_implicit_move_constructor,
Sebastian Redlf677ea32011-02-05 19:23:19 +00008084 oc_implicit_copy_assignment,
Sean Hunt82713172011-05-25 23:16:36 +00008085 oc_implicit_move_assignment,
Sebastian Redlf677ea32011-02-05 19:23:19 +00008086 oc_implicit_inherited_constructor
John McCall3c80f572010-01-12 02:15:36 +00008087};
8088
John McCall220ccbf2010-01-13 00:25:19 +00008089OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8090 FunctionDecl *Fn,
8091 std::string &Description) {
8092 bool isTemplate = false;
8093
8094 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8095 isTemplate = true;
8096 Description = S.getTemplateArgumentBindingsText(
8097 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8098 }
John McCallb1622a12010-01-06 09:43:14 +00008099
8100 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00008101 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00008102 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00008103
Sebastian Redlf677ea32011-02-05 19:23:19 +00008104 if (Ctor->getInheritedConstructor())
8105 return oc_implicit_inherited_constructor;
8106
Sean Hunt82713172011-05-25 23:16:36 +00008107 if (Ctor->isDefaultConstructor())
8108 return oc_implicit_default_constructor;
8109
8110 if (Ctor->isMoveConstructor())
8111 return oc_implicit_move_constructor;
8112
8113 assert(Ctor->isCopyConstructor() &&
8114 "unexpected sort of implicit constructor");
8115 return oc_implicit_copy_constructor;
John McCallb1622a12010-01-06 09:43:14 +00008116 }
8117
8118 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8119 // This actually gets spelled 'candidate function' for now, but
8120 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00008121 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00008122 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00008123
Sean Hunt82713172011-05-25 23:16:36 +00008124 if (Meth->isMoveAssignmentOperator())
8125 return oc_implicit_move_assignment;
8126
Douglas Gregoref7d78b2012-02-10 08:36:38 +00008127 if (Meth->isCopyAssignmentOperator())
8128 return oc_implicit_copy_assignment;
8129
8130 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8131 return oc_method;
John McCall3c80f572010-01-12 02:15:36 +00008132 }
8133
John McCall220ccbf2010-01-13 00:25:19 +00008134 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00008135}
8136
Larisse Voufo43847122013-07-19 23:00:19 +00008137void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
Sebastian Redlf677ea32011-02-05 19:23:19 +00008138 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8139 if (!Ctor) return;
8140
8141 Ctor = Ctor->getInheritedConstructor();
8142 if (!Ctor) return;
8143
8144 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8145}
8146
John McCall3c80f572010-01-12 02:15:36 +00008147} // end anonymous namespace
8148
8149// Notes the location of an overload candidate.
Richard Trieu6efd4c52011-11-23 22:32:32 +00008150void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCall220ccbf2010-01-13 00:25:19 +00008151 std::string FnDesc;
8152 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieu6efd4c52011-11-23 22:32:32 +00008153 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8154 << (unsigned) K << FnDesc;
8155 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8156 Diag(Fn->getLocation(), PD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008157 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallb1622a12010-01-06 09:43:14 +00008158}
8159
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008160//Notes the location of all overload candidates designated through
8161// OverloadedExpr
Richard Trieu6efd4c52011-11-23 22:32:32 +00008162void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008163 assert(OverloadedExpr->getType() == Context.OverloadTy);
8164
8165 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8166 OverloadExpr *OvlExpr = Ovl.Expression;
8167
8168 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8169 IEnd = OvlExpr->decls_end();
8170 I != IEnd; ++I) {
8171 if (FunctionTemplateDecl *FunTmpl =
8172 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00008173 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008174 } else if (FunctionDecl *Fun
8175 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00008176 NoteOverloadCandidate(Fun, DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008177 }
8178 }
8179}
8180
John McCall1d318332010-01-12 00:44:57 +00008181/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8182/// "lead" diagnostic; it will be given two arguments, the source and
8183/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00008184void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8185 Sema &S,
8186 SourceLocation CaretLoc,
8187 const PartialDiagnostic &PDiag) const {
8188 S.Diag(CaretLoc, PDiag)
8189 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay45a37da2012-11-08 20:50:02 +00008190 // FIXME: The note limiting machinery is borrowed from
8191 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8192 // refactoring here.
8193 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8194 unsigned CandsShown = 0;
8195 AmbiguousConversionSequence::const_iterator I, E;
8196 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8197 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8198 break;
8199 ++CandsShown;
John McCall120d63c2010-08-24 20:38:10 +00008200 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00008201 }
Matt Beaumont-Gay45a37da2012-11-08 20:50:02 +00008202 if (I != E)
8203 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall81201622010-01-08 04:41:39 +00008204}
8205
John McCall1d318332010-01-12 00:44:57 +00008206namespace {
8207
John McCalladbb8f82010-01-13 09:16:55 +00008208void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8209 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8210 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00008211 assert(Cand->Function && "for now, candidate must be a function");
8212 FunctionDecl *Fn = Cand->Function;
8213
8214 // There's a conversion slot for the object argument if this is a
8215 // non-constructor method. Note that 'I' corresponds the
8216 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00008217 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00008218 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00008219 if (I == 0)
8220 isObjectArgument = true;
8221 else
8222 I--;
John McCall220ccbf2010-01-13 00:25:19 +00008223 }
8224
John McCall220ccbf2010-01-13 00:25:19 +00008225 std::string FnDesc;
8226 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8227
John McCalladbb8f82010-01-13 09:16:55 +00008228 Expr *FromExpr = Conv.Bad.FromExpr;
8229 QualType FromTy = Conv.Bad.getFromType();
8230 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00008231
John McCall5920dbb2010-02-02 02:42:52 +00008232 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00008233 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00008234 Expr *E = FromExpr->IgnoreParens();
8235 if (isa<UnaryOperator>(E))
8236 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00008237 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00008238
8239 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8240 << (unsigned) FnKind << FnDesc
8241 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8242 << ToTy << Name << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008243 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall5920dbb2010-02-02 02:42:52 +00008244 return;
8245 }
8246
John McCall258b2032010-01-23 08:10:49 +00008247 // Do some hand-waving analysis to see if the non-viability is due
8248 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00008249 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8250 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8251 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8252 CToTy = RT->getPointeeType();
8253 else {
8254 // TODO: detect and diagnose the full richness of const mismatches.
8255 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8256 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8257 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8258 }
8259
8260 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8261 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall651f3ee2010-01-14 03:28:57 +00008262 Qualifiers FromQs = CFromTy.getQualifiers();
8263 Qualifiers ToQs = CToTy.getQualifiers();
8264
8265 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8266 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8267 << (unsigned) FnKind << FnDesc
8268 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8269 << FromTy
8270 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8271 << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008272 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008273 return;
8274 }
8275
John McCallf85e1932011-06-15 23:02:42 +00008276 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00008277 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCallf85e1932011-06-15 23:02:42 +00008278 << (unsigned) FnKind << FnDesc
8279 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8280 << FromTy
8281 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8282 << (unsigned) isObjectArgument << I+1;
8283 MaybeEmitInheritedConstructorNote(S, Fn);
8284 return;
8285 }
8286
Douglas Gregor028ea4b2011-04-26 23:16:46 +00008287 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8288 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8289 << (unsigned) FnKind << FnDesc
8290 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8291 << FromTy
8292 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8293 << (unsigned) isObjectArgument << I+1;
8294 MaybeEmitInheritedConstructorNote(S, Fn);
8295 return;
8296 }
8297
John McCall651f3ee2010-01-14 03:28:57 +00008298 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8299 assert(CVR && "unexpected qualifiers mismatch");
8300
8301 if (isObjectArgument) {
8302 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8303 << (unsigned) FnKind << FnDesc
8304 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8305 << FromTy << (CVR - 1);
8306 } else {
8307 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8308 << (unsigned) FnKind << FnDesc
8309 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8310 << FromTy << (CVR - 1) << I+1;
8311 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008312 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008313 return;
8314 }
8315
Sebastian Redlfd2a00a2011-09-24 17:48:32 +00008316 // Special diagnostic for failure to convert an initializer list, since
8317 // telling the user that it has type void is not useful.
8318 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8319 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8320 << (unsigned) FnKind << FnDesc
8321 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8322 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8323 MaybeEmitInheritedConstructorNote(S, Fn);
8324 return;
8325 }
8326
John McCall258b2032010-01-23 08:10:49 +00008327 // Diagnose references or pointers to incomplete types differently,
8328 // since it's far from impossible that the incompleteness triggered
8329 // the failure.
8330 QualType TempFromTy = FromTy.getNonReferenceType();
8331 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8332 TempFromTy = PTy->getPointeeType();
8333 if (TempFromTy->isIncompleteType()) {
8334 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8335 << (unsigned) FnKind << FnDesc
8336 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8337 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008338 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall258b2032010-01-23 08:10:49 +00008339 return;
8340 }
8341
Douglas Gregor85789812010-06-30 23:01:39 +00008342 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008343 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00008344 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8345 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8346 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8347 FromPtrTy->getPointeeType()) &&
8348 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8349 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008350 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor85789812010-06-30 23:01:39 +00008351 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008352 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00008353 }
8354 } else if (const ObjCObjectPointerType *FromPtrTy
8355 = FromTy->getAs<ObjCObjectPointerType>()) {
8356 if (const ObjCObjectPointerType *ToPtrTy
8357 = ToTy->getAs<ObjCObjectPointerType>())
8358 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8359 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8360 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8361 FromPtrTy->getPointeeType()) &&
8362 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008363 BaseToDerivedConversion = 2;
8364 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008365 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8366 !FromTy->isIncompleteType() &&
8367 !ToRefTy->getPointeeType()->isIncompleteType() &&
8368 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8369 BaseToDerivedConversion = 3;
8370 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8371 ToTy.getNonReferenceType().getCanonicalType() ==
8372 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008373 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8374 << (unsigned) FnKind << FnDesc
8375 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8376 << (unsigned) isObjectArgument << I + 1;
8377 MaybeEmitInheritedConstructorNote(S, Fn);
8378 return;
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008379 }
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008380 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008381
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008382 if (BaseToDerivedConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008383 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008384 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00008385 << (unsigned) FnKind << FnDesc
8386 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008387 << (BaseToDerivedConversion - 1)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008388 << FromTy << ToTy << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008389 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor85789812010-06-30 23:01:39 +00008390 return;
8391 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008392
Fariborz Jahanian909bcb32011-07-20 17:14:09 +00008393 if (isa<ObjCObjectPointerType>(CFromTy) &&
8394 isa<PointerType>(CToTy)) {
8395 Qualifiers FromQs = CFromTy.getQualifiers();
8396 Qualifiers ToQs = CToTy.getQualifiers();
8397 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8398 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8399 << (unsigned) FnKind << FnDesc
8400 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8401 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8402 MaybeEmitInheritedConstructorNote(S, Fn);
8403 return;
8404 }
8405 }
8406
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008407 // Emit the generic diagnostic and, optionally, add the hints to it.
8408 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8409 FDiag << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00008410 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008411 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8412 << (unsigned) (Cand->Fix.Kind);
8413
8414 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer1136ef02012-01-14 21:05:10 +00008415 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8416 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008417 FDiag << *HI;
8418 S.Diag(Fn->getLocation(), FDiag);
8419
Sebastian Redlf677ea32011-02-05 19:23:19 +00008420 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalladbb8f82010-01-13 09:16:55 +00008421}
8422
Larisse Voufo43847122013-07-19 23:00:19 +00008423/// Additional arity mismatch diagnosis specific to a function overload
8424/// candidates. This is not covered by the more general DiagnoseArityMismatch()
8425/// over a candidate in any candidate set.
8426bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8427 unsigned NumArgs) {
John McCalladbb8f82010-01-13 09:16:55 +00008428 FunctionDecl *Fn = Cand->Function;
John McCalladbb8f82010-01-13 09:16:55 +00008429 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008430
Douglas Gregor439d3c32011-05-05 00:13:13 +00008431 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo43847122013-07-19 23:00:19 +00008432 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor439d3c32011-05-05 00:13:13 +00008433 // right number of arguments, because only overloaded operators have
8434 // the weird behavior of overloading member and non-member functions.
8435 // Just don't report anything.
8436 if (Fn->isInvalidDecl() &&
8437 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo43847122013-07-19 23:00:19 +00008438 return true;
8439
8440 if (NumArgs < MinParams) {
8441 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8442 (Cand->FailureKind == ovl_fail_bad_deduction &&
8443 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8444 } else {
8445 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8446 (Cand->FailureKind == ovl_fail_bad_deduction &&
8447 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8448 }
8449
8450 return false;
8451}
8452
8453/// General arity mismatch diagnosis over a candidate in a candidate set.
8454void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
8455 assert(isa<FunctionDecl>(D) &&
8456 "The templated declaration should at least be a function"
8457 " when diagnosing bad template argument deduction due to too many"
8458 " or too few arguments");
8459
8460 FunctionDecl *Fn = cast<FunctionDecl>(D);
8461
8462 // TODO: treat calls to a missing default constructor as a special case
8463 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8464 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor439d3c32011-05-05 00:13:13 +00008465
John McCalladbb8f82010-01-13 09:16:55 +00008466 // at least / at most / exactly
8467 unsigned mode, modeCount;
8468 if (NumFormalArgs < MinParams) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008469 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00008470 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00008471 mode = 0; // "at least"
8472 else
8473 mode = 2; // "exactly"
8474 modeCount = MinParams;
8475 } else {
John McCalladbb8f82010-01-13 09:16:55 +00008476 if (MinParams != FnTy->getNumArgs())
8477 mode = 1; // "at most"
8478 else
8479 mode = 2; // "exactly"
8480 modeCount = FnTy->getNumArgs();
8481 }
8482
8483 std::string Description;
8484 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8485
Richard Smithf7b80562012-05-11 05:16:41 +00008486 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8487 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8488 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8489 << Fn->getParamDecl(0) << NumFormalArgs;
8490 else
8491 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8492 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8493 << modeCount << NumFormalArgs;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008494 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008495}
8496
Larisse Voufo43847122013-07-19 23:00:19 +00008497/// Arity mismatch diagnosis specific to a function overload candidate.
8498void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8499 unsigned NumFormalArgs) {
8500 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
8501 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
8502}
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008503
Larisse Voufo43847122013-07-19 23:00:19 +00008504TemplateDecl *getDescribedTemplate(Decl *Templated) {
8505 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
8506 return FD->getDescribedFunctionTemplate();
8507 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
8508 return RD->getDescribedClassTemplate();
8509
8510 llvm_unreachable("Unsupported: Getting the described template declaration"
8511 " for bad deduction diagnosis");
8512}
8513
8514/// Diagnose a failed template-argument deduction.
8515void DiagnoseBadDeduction(Sema &S, Decl *Templated,
8516 DeductionFailureInfo &DeductionFailure,
8517 unsigned NumArgs) {
8518 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00008519 NamedDecl *ParamD;
8520 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8521 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8522 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo43847122013-07-19 23:00:19 +00008523 switch (DeductionFailure.Result) {
John McCall342fec42010-02-01 18:53:26 +00008524 case Sema::TDK_Success:
8525 llvm_unreachable("TDK_success while diagnosing bad deduction");
8526
8527 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00008528 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo43847122013-07-19 23:00:19 +00008529 S.Diag(Templated->getLocation(),
8530 diag::note_ovl_candidate_incomplete_deduction)
8531 << ParamD->getDeclName();
8532 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall342fec42010-02-01 18:53:26 +00008533 return;
8534 }
8535
John McCall57e97782010-08-05 09:05:08 +00008536 case Sema::TDK_Underqualified: {
8537 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8538 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8539
Larisse Voufo43847122013-07-19 23:00:19 +00008540 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall57e97782010-08-05 09:05:08 +00008541
8542 // Param will have been canonicalized, but it should just be a
8543 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00008544 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00008545 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00008546 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00008547 assert(S.Context.hasSameType(Param, NonCanonParam));
8548
8549 // Arg has also been canonicalized, but there's nothing we can do
8550 // about that. It also doesn't matter as much, because it won't
8551 // have any template parameters in it (because deduction isn't
8552 // done on dependent types).
Larisse Voufo43847122013-07-19 23:00:19 +00008553 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall57e97782010-08-05 09:05:08 +00008554
Larisse Voufo43847122013-07-19 23:00:19 +00008555 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
8556 << ParamD->getDeclName() << Arg << NonCanonParam;
8557 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall57e97782010-08-05 09:05:08 +00008558 return;
8559 }
8560
8561 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00008562 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00008563 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008564 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008565 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008566 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008567 which = 1;
8568 else {
Douglas Gregora9333192010-05-08 17:41:32 +00008569 which = 2;
8570 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008571
Larisse Voufo43847122013-07-19 23:00:19 +00008572 S.Diag(Templated->getLocation(),
8573 diag::note_ovl_candidate_inconsistent_deduction)
8574 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
8575 << *DeductionFailure.getSecondArg();
8576 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregora9333192010-05-08 17:41:32 +00008577 return;
8578 }
Douglas Gregora18592e2010-05-08 18:13:28 +00008579
Douglas Gregorf1a84452010-05-08 19:15:54 +00008580 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008581 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregorf1a84452010-05-08 19:15:54 +00008582 if (ParamD->getDeclName())
Larisse Voufo43847122013-07-19 23:00:19 +00008583 S.Diag(Templated->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008584 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo43847122013-07-19 23:00:19 +00008585 << ParamD->getDeclName();
Douglas Gregorf1a84452010-05-08 19:15:54 +00008586 else {
8587 int index = 0;
8588 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8589 index = TTP->getIndex();
8590 else if (NonTypeTemplateParmDecl *NTTP
8591 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8592 index = NTTP->getIndex();
8593 else
8594 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo43847122013-07-19 23:00:19 +00008595 S.Diag(Templated->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008596 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo43847122013-07-19 23:00:19 +00008597 << (index + 1);
Douglas Gregorf1a84452010-05-08 19:15:54 +00008598 }
Larisse Voufo43847122013-07-19 23:00:19 +00008599 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregorf1a84452010-05-08 19:15:54 +00008600 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008601
Douglas Gregora18592e2010-05-08 18:13:28 +00008602 case Sema::TDK_TooManyArguments:
8603 case Sema::TDK_TooFewArguments:
Larisse Voufo43847122013-07-19 23:00:19 +00008604 DiagnoseArityMismatch(S, Templated, NumArgs);
Douglas Gregora18592e2010-05-08 18:13:28 +00008605 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00008606
8607 case Sema::TDK_InstantiationDepth:
Larisse Voufo43847122013-07-19 23:00:19 +00008608 S.Diag(Templated->getLocation(),
8609 diag::note_ovl_candidate_instantiation_depth);
8610 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregorec20f462010-05-08 20:07:26 +00008611 return;
8612
8613 case Sema::TDK_SubstitutionFailure: {
Richard Smithb8590f32012-05-07 09:03:25 +00008614 // Format the template argument list into the argument string.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008615 SmallString<128> TemplateArgString;
Richard Smithb8590f32012-05-07 09:03:25 +00008616 if (TemplateArgumentList *Args =
Larisse Voufo43847122013-07-19 23:00:19 +00008617 DeductionFailure.getTemplateArgumentList()) {
Richard Smithb8590f32012-05-07 09:03:25 +00008618 TemplateArgString = " ";
8619 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo43847122013-07-19 23:00:19 +00008620 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smithb8590f32012-05-07 09:03:25 +00008621 }
8622
Richard Smith4493c0a2012-05-09 05:17:00 +00008623 // If this candidate was disabled by enable_if, say so.
Larisse Voufo43847122013-07-19 23:00:19 +00008624 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith4493c0a2012-05-09 05:17:00 +00008625 if (PDiag && PDiag->second.getDiagID() ==
8626 diag::err_typename_nested_not_found_enable_if) {
8627 // FIXME: Use the source range of the condition, and the fully-qualified
8628 // name of the enable_if template. These are both present in PDiag.
8629 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8630 << "'enable_if'" << TemplateArgString;
8631 return;
8632 }
8633
Richard Smithb8590f32012-05-07 09:03:25 +00008634 // Format the SFINAE diagnostic into the argument string.
8635 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8636 // formatted message in another diagnostic.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008637 SmallString<128> SFINAEArgString;
Richard Smithb8590f32012-05-07 09:03:25 +00008638 SourceRange R;
Richard Smith4493c0a2012-05-09 05:17:00 +00008639 if (PDiag) {
Richard Smithb8590f32012-05-07 09:03:25 +00008640 SFINAEArgString = ": ";
8641 R = SourceRange(PDiag->first, PDiag->first);
8642 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8643 }
8644
Larisse Voufo43847122013-07-19 23:00:19 +00008645 S.Diag(Templated->getLocation(),
8646 diag::note_ovl_candidate_substitution_failure)
8647 << TemplateArgString << SFINAEArgString << R;
8648 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregorec20f462010-05-08 20:07:26 +00008649 return;
8650 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008651
Richard Smith0efa62f2013-01-31 04:03:12 +00008652 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo43847122013-07-19 23:00:19 +00008653 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
8654 S.Diag(Templated->getLocation(),
Richard Smith0efa62f2013-01-31 04:03:12 +00008655 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo43847122013-07-19 23:00:19 +00008656 << R.Expression->getName();
Richard Smith0efa62f2013-01-31 04:03:12 +00008657 return;
8658 }
8659
Richard Trieueef35f82013-04-08 21:11:40 +00008660 case Sema::TDK_NonDeducedMismatch: {
Richard Smith29805ca2013-01-31 05:19:49 +00008661 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo43847122013-07-19 23:00:19 +00008662 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
8663 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieueef35f82013-04-08 21:11:40 +00008664 if (FirstTA.getKind() == TemplateArgument::Template &&
8665 SecondTA.getKind() == TemplateArgument::Template) {
8666 TemplateName FirstTN = FirstTA.getAsTemplate();
8667 TemplateName SecondTN = SecondTA.getAsTemplate();
8668 if (FirstTN.getKind() == TemplateName::Template &&
8669 SecondTN.getKind() == TemplateName::Template) {
8670 if (FirstTN.getAsTemplateDecl()->getName() ==
8671 SecondTN.getAsTemplateDecl()->getName()) {
8672 // FIXME: This fixes a bad diagnostic where both templates are named
8673 // the same. This particular case is a bit difficult since:
8674 // 1) It is passed as a string to the diagnostic printer.
8675 // 2) The diagnostic printer only attempts to find a better
8676 // name for types, not decls.
8677 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo43847122013-07-19 23:00:19 +00008678 S.Diag(Templated->getLocation(),
Richard Trieueef35f82013-04-08 21:11:40 +00008679 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
8680 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
8681 return;
8682 }
8683 }
8684 }
Larisse Voufo43847122013-07-19 23:00:19 +00008685 S.Diag(Templated->getLocation(),
8686 diag::note_ovl_candidate_non_deduced_mismatch)
8687 << FirstTA << SecondTA;
Richard Smith29805ca2013-01-31 05:19:49 +00008688 return;
Richard Trieueef35f82013-04-08 21:11:40 +00008689 }
John McCall342fec42010-02-01 18:53:26 +00008690 // TODO: diagnose these individually, then kill off
8691 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith29805ca2013-01-31 05:19:49 +00008692 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo43847122013-07-19 23:00:19 +00008693 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
8694 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall342fec42010-02-01 18:53:26 +00008695 return;
8696 }
8697}
8698
Larisse Voufo43847122013-07-19 23:00:19 +00008699/// Diagnose a failed template-argument deduction, for function calls.
8700void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, unsigned NumArgs) {
8701 unsigned TDK = Cand->DeductionFailure.Result;
8702 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
8703 if (CheckArityMismatch(S, Cand, NumArgs))
8704 return;
8705 }
8706 DiagnoseBadDeduction(S, Cand->Function, // pattern
8707 Cand->DeductionFailure, NumArgs);
8708}
8709
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008710/// CUDA: diagnose an invalid call across targets.
8711void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8712 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8713 FunctionDecl *Callee = Cand->Function;
8714
8715 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8716 CalleeTarget = S.IdentifyCUDATarget(Callee);
8717
8718 std::string FnDesc;
8719 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8720
8721 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8722 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8723}
8724
John McCall342fec42010-02-01 18:53:26 +00008725/// Generates a 'note' diagnostic for an overload candidate. We've
8726/// already generated a primary error at the call site.
8727///
8728/// It really does need to be a single diagnostic with its caret
8729/// pointed at the candidate declaration. Yes, this creates some
8730/// major challenges of technical writing. Yes, this makes pointing
8731/// out problems with specific arguments quite awkward. It's still
8732/// better than generating twenty screens of text for every failed
8733/// overload.
8734///
8735/// It would be great to be able to express per-candidate problems
8736/// more richly for those diagnostic clients that cared, but we'd
8737/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00008738void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008739 unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00008740 FunctionDecl *Fn = Cand->Function;
8741
John McCall81201622010-01-08 04:41:39 +00008742 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008743 if (Cand->Viable && (Fn->isDeleted() ||
8744 S.isFunctionConsideredUnavailable(Fn))) {
John McCall220ccbf2010-01-13 00:25:19 +00008745 std::string FnDesc;
8746 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00008747
8748 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith5bdaac52012-04-02 20:59:25 +00008749 << FnKind << FnDesc
8750 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008751 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalla1d7d622010-01-08 00:58:21 +00008752 return;
John McCall81201622010-01-08 04:41:39 +00008753 }
8754
John McCall220ccbf2010-01-13 00:25:19 +00008755 // We don't really have anything else to say about viable candidates.
8756 if (Cand->Viable) {
8757 S.NoteOverloadCandidate(Fn);
8758 return;
8759 }
John McCall1d318332010-01-12 00:44:57 +00008760
John McCalladbb8f82010-01-13 09:16:55 +00008761 switch (Cand->FailureKind) {
8762 case ovl_fail_too_many_arguments:
8763 case ovl_fail_too_few_arguments:
8764 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00008765
John McCalladbb8f82010-01-13 09:16:55 +00008766 case ovl_fail_bad_deduction:
Ahmed Charles13a140c2012-02-25 11:00:22 +00008767 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall342fec42010-02-01 18:53:26 +00008768
John McCall717e8912010-01-23 05:17:32 +00008769 case ovl_fail_trivial_conversion:
8770 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00008771 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00008772 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008773
John McCallb1bdc622010-02-25 01:37:24 +00008774 case ovl_fail_bad_conversion: {
8775 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008776 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00008777 if (Cand->Conversions[I].isBad())
8778 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008779
John McCalladbb8f82010-01-13 09:16:55 +00008780 // FIXME: this currently happens when we're called from SemaInit
8781 // when user-conversion overload fails. Figure out how to handle
8782 // those conditions and diagnose them well.
8783 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008784 }
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008785
8786 case ovl_fail_bad_target:
8787 return DiagnoseBadTarget(S, Cand);
John McCallb1bdc622010-02-25 01:37:24 +00008788 }
John McCalla1d7d622010-01-08 00:58:21 +00008789}
8790
8791void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8792 // Desugar the type of the surrogate down to a function type,
8793 // retaining as many typedefs as possible while still showing
8794 // the function type (and, therefore, its parameter types).
8795 QualType FnType = Cand->Surrogate->getConversionType();
8796 bool isLValueReference = false;
8797 bool isRValueReference = false;
8798 bool isPointer = false;
8799 if (const LValueReferenceType *FnTypeRef =
8800 FnType->getAs<LValueReferenceType>()) {
8801 FnType = FnTypeRef->getPointeeType();
8802 isLValueReference = true;
8803 } else if (const RValueReferenceType *FnTypeRef =
8804 FnType->getAs<RValueReferenceType>()) {
8805 FnType = FnTypeRef->getPointeeType();
8806 isRValueReference = true;
8807 }
8808 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8809 FnType = FnTypePtr->getPointeeType();
8810 isPointer = true;
8811 }
8812 // Desugar down to a function type.
8813 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8814 // Reconstruct the pointer/reference as appropriate.
8815 if (isPointer) FnType = S.Context.getPointerType(FnType);
8816 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8817 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8818
8819 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8820 << FnType;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008821 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalla1d7d622010-01-08 00:58:21 +00008822}
8823
8824void NoteBuiltinOperatorCandidate(Sema &S,
David Blaikie0bea8632012-10-08 01:11:04 +00008825 StringRef Opc,
John McCalla1d7d622010-01-08 00:58:21 +00008826 SourceLocation OpLoc,
8827 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008828 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalla1d7d622010-01-08 00:58:21 +00008829 std::string TypeStr("operator");
8830 TypeStr += Opc;
8831 TypeStr += "(";
8832 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008833 if (Cand->NumConversions == 1) {
John McCalla1d7d622010-01-08 00:58:21 +00008834 TypeStr += ")";
8835 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8836 } else {
8837 TypeStr += ", ";
8838 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8839 TypeStr += ")";
8840 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8841 }
8842}
8843
8844void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8845 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008846 unsigned NoOperands = Cand->NumConversions;
John McCalla1d7d622010-01-08 00:58:21 +00008847 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8848 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00008849 if (ICS.isBad()) break; // all meaningless after first invalid
8850 if (!ICS.isAmbiguous()) continue;
8851
John McCall120d63c2010-08-24 20:38:10 +00008852 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008853 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00008854 }
8855}
8856
Larisse Voufo43847122013-07-19 23:00:19 +00008857static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall1b77e732010-01-15 23:32:50 +00008858 if (Cand->Function)
8859 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00008860 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00008861 return Cand->Surrogate->getLocation();
8862 return SourceLocation();
8863}
8864
Larisse Voufo43847122013-07-19 23:00:19 +00008865static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth78bf6802011-09-10 00:51:24 +00008866 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008867 case Sema::TDK_Success:
David Blaikieb219cfc2011-09-23 05:06:16 +00008868 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008869
Douglas Gregorae19fbb2012-09-13 21:01:57 +00008870 case Sema::TDK_Invalid:
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008871 case Sema::TDK_Incomplete:
8872 return 1;
8873
8874 case Sema::TDK_Underqualified:
8875 case Sema::TDK_Inconsistent:
8876 return 2;
8877
8878 case Sema::TDK_SubstitutionFailure:
8879 case Sema::TDK_NonDeducedMismatch:
Richard Smith29805ca2013-01-31 05:19:49 +00008880 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008881 return 3;
8882
8883 case Sema::TDK_InstantiationDepth:
8884 case Sema::TDK_FailedOverloadResolution:
8885 return 4;
8886
8887 case Sema::TDK_InvalidExplicitArguments:
8888 return 5;
8889
8890 case Sema::TDK_TooManyArguments:
8891 case Sema::TDK_TooFewArguments:
8892 return 6;
8893 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008894 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008895}
8896
John McCallbf65c0b2010-01-12 00:48:53 +00008897struct CompareOverloadCandidatesForDisplay {
8898 Sema &S;
8899 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00008900
8901 bool operator()(const OverloadCandidate *L,
8902 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00008903 // Fast-path this check.
8904 if (L == R) return false;
8905
John McCall81201622010-01-08 04:41:39 +00008906 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00008907 if (L->Viable) {
8908 if (!R->Viable) return true;
8909
8910 // TODO: introduce a tri-valued comparison for overload
8911 // candidates. Would be more worthwhile if we had a sort
8912 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00008913 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8914 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00008915 } else if (R->Viable)
8916 return false;
John McCall81201622010-01-08 04:41:39 +00008917
John McCall1b77e732010-01-15 23:32:50 +00008918 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00008919
John McCall1b77e732010-01-15 23:32:50 +00008920 // Criteria by which we can sort non-viable candidates:
8921 if (!L->Viable) {
8922 // 1. Arity mismatches come after other candidates.
8923 if (L->FailureKind == ovl_fail_too_many_arguments ||
8924 L->FailureKind == ovl_fail_too_few_arguments)
8925 return false;
8926 if (R->FailureKind == ovl_fail_too_many_arguments ||
8927 R->FailureKind == ovl_fail_too_few_arguments)
8928 return true;
John McCall81201622010-01-08 04:41:39 +00008929
John McCall717e8912010-01-23 05:17:32 +00008930 // 2. Bad conversions come first and are ordered by the number
8931 // of bad conversions and quality of good conversions.
8932 if (L->FailureKind == ovl_fail_bad_conversion) {
8933 if (R->FailureKind != ovl_fail_bad_conversion)
8934 return true;
8935
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008936 // The conversion that can be fixed with a smaller number of changes,
8937 // comes first.
8938 unsigned numLFixes = L->Fix.NumConversionsFixed;
8939 unsigned numRFixes = R->Fix.NumConversionsFixed;
8940 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8941 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008942 if (numLFixes != numRFixes) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008943 if (numLFixes < numRFixes)
8944 return true;
8945 else
8946 return false;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008947 }
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008948
John McCall717e8912010-01-23 05:17:32 +00008949 // If there's any ordering between the defined conversions...
8950 // FIXME: this might not be transitive.
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008951 assert(L->NumConversions == R->NumConversions);
John McCall717e8912010-01-23 05:17:32 +00008952
8953 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00008954 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008955 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00008956 switch (CompareImplicitConversionSequences(S,
8957 L->Conversions[I],
8958 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00008959 case ImplicitConversionSequence::Better:
8960 leftBetter++;
8961 break;
8962
8963 case ImplicitConversionSequence::Worse:
8964 leftBetter--;
8965 break;
8966
8967 case ImplicitConversionSequence::Indistinguishable:
8968 break;
8969 }
8970 }
8971 if (leftBetter > 0) return true;
8972 if (leftBetter < 0) return false;
8973
8974 } else if (R->FailureKind == ovl_fail_bad_conversion)
8975 return false;
8976
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008977 if (L->FailureKind == ovl_fail_bad_deduction) {
8978 if (R->FailureKind != ovl_fail_bad_deduction)
8979 return true;
8980
8981 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8982 return RankDeductionFailure(L->DeductionFailure)
Eli Friedmance1846e2011-10-14 23:10:30 +00008983 < RankDeductionFailure(R->DeductionFailure);
Eli Friedman1c522f72011-10-14 21:52:24 +00008984 } else if (R->FailureKind == ovl_fail_bad_deduction)
8985 return false;
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008986
John McCall1b77e732010-01-15 23:32:50 +00008987 // TODO: others?
8988 }
8989
8990 // Sort everything else by location.
8991 SourceLocation LLoc = GetLocationForCandidate(L);
8992 SourceLocation RLoc = GetLocationForCandidate(R);
8993
8994 // Put candidates without locations (e.g. builtins) at the end.
8995 if (LLoc.isInvalid()) return false;
8996 if (RLoc.isInvalid()) return true;
8997
8998 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00008999 }
9000};
9001
John McCall717e8912010-01-23 05:17:32 +00009002/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009003/// computes up to the first. Produces the FixIt set if possible.
John McCall717e8912010-01-23 05:17:32 +00009004void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009005 ArrayRef<Expr *> Args) {
John McCall717e8912010-01-23 05:17:32 +00009006 assert(!Cand->Viable);
9007
9008 // Don't do anything on failures other than bad conversion.
9009 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9010
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009011 // We only want the FixIts if all the arguments can be corrected.
9012 bool Unfixable = false;
Anna Zaksf3546ee2011-07-28 19:46:48 +00009013 // Use a implicit copy initialization to check conversion fixes.
9014 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009015
John McCall717e8912010-01-23 05:17:32 +00009016 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00009017 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00009018 unsigned ConvCount = Cand->NumConversions;
John McCall717e8912010-01-23 05:17:32 +00009019 while (true) {
9020 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9021 ConvIdx++;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009022 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaksf3546ee2011-07-28 19:46:48 +00009023 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCall717e8912010-01-23 05:17:32 +00009024 break;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009025 }
John McCall717e8912010-01-23 05:17:32 +00009026 }
9027
9028 if (ConvIdx == ConvCount)
9029 return;
9030
John McCallb1bdc622010-02-25 01:37:24 +00009031 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9032 "remaining conversion is initialized?");
9033
Douglas Gregor23ef6c02010-04-16 17:45:54 +00009034 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00009035 // operation somehow.
9036 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00009037
9038 const FunctionProtoType* Proto;
9039 unsigned ArgIdx = ConvIdx;
9040
9041 if (Cand->IsSurrogate) {
9042 QualType ConvType
9043 = Cand->Surrogate->getConversionType().getNonReferenceType();
9044 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9045 ConvType = ConvPtrType->getPointeeType();
9046 Proto = ConvType->getAs<FunctionProtoType>();
9047 ArgIdx--;
9048 } else if (Cand->Function) {
9049 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9050 if (isa<CXXMethodDecl>(Cand->Function) &&
9051 !isa<CXXConstructorDecl>(Cand->Function))
9052 ArgIdx--;
9053 } else {
9054 // Builtin binary operator with a bad first conversion.
9055 assert(ConvCount <= 3);
9056 for (; ConvIdx != ConvCount; ++ConvIdx)
9057 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00009058 = TryCopyInitialization(S, Args[ConvIdx],
9059 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009060 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00009061 /*InOverloadResolution*/ true,
9062 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00009063 S.getLangOpts().ObjCAutoRefCount);
John McCall717e8912010-01-23 05:17:32 +00009064 return;
9065 }
9066
9067 // Fill in the rest of the conversions.
9068 unsigned NumArgsInProto = Proto->getNumArgs();
9069 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009070 if (ArgIdx < NumArgsInProto) {
John McCall717e8912010-01-23 05:17:32 +00009071 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00009072 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009073 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00009074 /*InOverloadResolution=*/true,
9075 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00009076 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009077 // Store the FixIt in the candidate if it exists.
9078 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaksf3546ee2011-07-28 19:46:48 +00009079 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009080 }
John McCall717e8912010-01-23 05:17:32 +00009081 else
9082 Cand->Conversions[ConvIdx].setEllipsis();
9083 }
9084}
9085
John McCalla1d7d622010-01-08 00:58:21 +00009086} // end anonymous namespace
9087
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00009088/// PrintOverloadCandidates - When overload resolution fails, prints
9089/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00009090/// set.
John McCall120d63c2010-08-24 20:38:10 +00009091void OverloadCandidateSet::NoteCandidates(Sema &S,
9092 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009093 ArrayRef<Expr *> Args,
David Blaikie0bea8632012-10-08 01:11:04 +00009094 StringRef Opc,
John McCall120d63c2010-08-24 20:38:10 +00009095 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00009096 // Sort the candidates by viability and position. Sorting directly would
9097 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00009098 SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00009099 if (OCD == OCD_AllCandidates) Cands.reserve(size());
9100 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00009101 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00009102 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00009103 else if (OCD == OCD_AllCandidates) {
Ahmed Charles13a140c2012-02-25 11:00:22 +00009104 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009105 if (Cand->Function || Cand->IsSurrogate)
9106 Cands.push_back(Cand);
9107 // Otherwise, this a non-viable builtin candidate. We do not, in general,
9108 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00009109 }
9110 }
9111
John McCallbf65c0b2010-01-12 00:48:53 +00009112 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00009113 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009114
John McCall1d318332010-01-12 00:44:57 +00009115 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00009116
Chris Lattner5f9e2722011-07-23 10:55:15 +00009117 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregordc7b6412012-10-23 23:11:23 +00009118 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009119 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00009120 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9121 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00009122
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009123 // Set an arbitrary limit on the number of candidate functions we'll spam
9124 // the user with. FIXME: This limit should depend on details of the
9125 // candidate list.
Douglas Gregordc7b6412012-10-23 23:11:23 +00009126 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009127 break;
9128 }
9129 ++CandsShown;
9130
John McCalla1d7d622010-01-08 00:58:21 +00009131 if (Cand->Function)
Ahmed Charles13a140c2012-02-25 11:00:22 +00009132 NoteFunctionCandidate(S, Cand, Args.size());
John McCalla1d7d622010-01-08 00:58:21 +00009133 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00009134 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009135 else {
9136 assert(Cand->Viable &&
9137 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00009138 // Generally we only see ambiguities including viable builtin
9139 // operators if overload resolution got screwed up by an
9140 // ambiguous user-defined conversion.
9141 //
9142 // FIXME: It's quite possible for different conversions to see
9143 // different ambiguities, though.
9144 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00009145 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00009146 ReportedAmbiguousConversions = true;
9147 }
John McCalla1d7d622010-01-08 00:58:21 +00009148
John McCall1d318332010-01-12 00:44:57 +00009149 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00009150 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00009151 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00009152 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009153
9154 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00009155 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00009156}
9157
Larisse Voufo43847122013-07-19 23:00:19 +00009158static SourceLocation
9159GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9160 return Cand->Specialization ? Cand->Specialization->getLocation()
9161 : SourceLocation();
9162}
9163
9164struct CompareTemplateSpecCandidatesForDisplay {
9165 Sema &S;
9166 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9167
9168 bool operator()(const TemplateSpecCandidate *L,
9169 const TemplateSpecCandidate *R) {
9170 // Fast-path this check.
9171 if (L == R)
9172 return false;
9173
9174 // Assuming that both candidates are not matches...
9175
9176 // Sort by the ranking of deduction failures.
9177 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9178 return RankDeductionFailure(L->DeductionFailure) <
9179 RankDeductionFailure(R->DeductionFailure);
9180
9181 // Sort everything else by location.
9182 SourceLocation LLoc = GetLocationForCandidate(L);
9183 SourceLocation RLoc = GetLocationForCandidate(R);
9184
9185 // Put candidates without locations (e.g. builtins) at the end.
9186 if (LLoc.isInvalid())
9187 return false;
9188 if (RLoc.isInvalid())
9189 return true;
9190
9191 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9192 }
9193};
9194
9195/// Diagnose a template argument deduction failure.
9196/// We are treating these failures as overload failures due to bad
9197/// deductions.
9198void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9199 DiagnoseBadDeduction(S, Specialization, // pattern
9200 DeductionFailure, /*NumArgs=*/0);
9201}
9202
9203void TemplateSpecCandidateSet::destroyCandidates() {
9204 for (iterator i = begin(), e = end(); i != e; ++i) {
9205 i->DeductionFailure.Destroy();
9206 }
9207}
9208
9209void TemplateSpecCandidateSet::clear() {
9210 destroyCandidates();
9211 Candidates.clear();
9212}
9213
9214/// NoteCandidates - When no template specialization match is found, prints
9215/// diagnostic messages containing the non-matching specializations that form
9216/// the candidate set.
9217/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9218/// OCD == OCD_AllCandidates and Cand->Viable == false.
9219void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9220 // Sort the candidates by position (assuming no candidate is a match).
9221 // Sorting directly would be prohibitive, so we make a set of pointers
9222 // and sort those.
9223 SmallVector<TemplateSpecCandidate *, 32> Cands;
9224 Cands.reserve(size());
9225 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9226 if (Cand->Specialization)
9227 Cands.push_back(Cand);
9228 // Otherwise, this is a non matching builtin candidate. We do not,
9229 // in general, want to list every possible builtin candidate.
9230 }
9231
9232 std::sort(Cands.begin(), Cands.end(),
9233 CompareTemplateSpecCandidatesForDisplay(S));
9234
9235 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9236 // for generalization purposes (?).
9237 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9238
9239 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9240 unsigned CandsShown = 0;
9241 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9242 TemplateSpecCandidate *Cand = *I;
9243
9244 // Set an arbitrary limit on the number of candidates we'll spam
9245 // the user with. FIXME: This limit should depend on details of the
9246 // candidate list.
9247 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9248 break;
9249 ++CandsShown;
9250
9251 assert(Cand->Specialization &&
9252 "Non-matching built-in candidates are not added to Cands.");
9253 Cand->NoteDeductionFailure(S);
9254 }
9255
9256 if (I != E)
9257 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9258}
9259
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009260// [PossiblyAFunctionType] --> [Return]
9261// NonFunctionType --> NonFunctionType
9262// R (A) --> R(A)
9263// R (*)(A) --> R (A)
9264// R (&)(A) --> R (A)
9265// R (S::*)(A) --> R (A)
9266QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9267 QualType Ret = PossiblyAFunctionType;
9268 if (const PointerType *ToTypePtr =
9269 PossiblyAFunctionType->getAs<PointerType>())
9270 Ret = ToTypePtr->getPointeeType();
9271 else if (const ReferenceType *ToTypeRef =
9272 PossiblyAFunctionType->getAs<ReferenceType>())
9273 Ret = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00009274 else if (const MemberPointerType *MemTypePtr =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009275 PossiblyAFunctionType->getAs<MemberPointerType>())
9276 Ret = MemTypePtr->getPointeeType();
9277 Ret =
9278 Context.getCanonicalType(Ret).getUnqualifiedType();
9279 return Ret;
9280}
Douglas Gregor904eed32008-11-10 20:40:00 +00009281
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009282// A helper class to help with address of function resolution
9283// - allows us to avoid passing around all those ugly parameters
9284class AddressOfFunctionResolver
9285{
9286 Sema& S;
9287 Expr* SourceExpr;
9288 const QualType& TargetType;
9289 QualType TargetFunctionType; // Extracted function type from target type
9290
9291 bool Complain;
9292 //DeclAccessPair& ResultFunctionAccessPair;
9293 ASTContext& Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009294
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009295 bool TargetTypeIsNonStaticMemberFunction;
9296 bool FoundNonTemplateFunction;
David Majnemer576a9af2013-08-01 06:13:59 +00009297 bool StaticMemberFunctionFromBoundPointer;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009298
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009299 OverloadExpr::FindResult OvlExprInfo;
9300 OverloadExpr *OvlExpr;
9301 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009302 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo43847122013-07-19 23:00:19 +00009303 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009304
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009305public:
Larisse Voufo43847122013-07-19 23:00:19 +00009306 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9307 const QualType &TargetType, bool Complain)
9308 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9309 Complain(Complain), Context(S.getASTContext()),
9310 TargetTypeIsNonStaticMemberFunction(
9311 !!TargetType->getAs<MemberPointerType>()),
9312 FoundNonTemplateFunction(false),
David Majnemer576a9af2013-08-01 06:13:59 +00009313 StaticMemberFunctionFromBoundPointer(false),
Larisse Voufo43847122013-07-19 23:00:19 +00009314 OvlExprInfo(OverloadExpr::find(SourceExpr)),
9315 OvlExpr(OvlExprInfo.Expression),
9316 FailedCandidates(OvlExpr->getNameLoc()) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009317 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruth90434232011-03-29 08:08:18 +00009318
David Majnemer576a9af2013-08-01 06:13:59 +00009319 if (TargetFunctionType->isFunctionType()) {
9320 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9321 if (!UME->isImplicitAccess() &&
9322 !S.ResolveSingleFunctionTemplateSpecialization(UME))
9323 StaticMemberFunctionFromBoundPointer = true;
9324 } else if (OvlExpr->hasExplicitTemplateArgs()) {
9325 DeclAccessPair dap;
9326 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9327 OvlExpr, false, &dap)) {
9328 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9329 if (!Method->isStatic()) {
9330 // If the target type is a non-function type and the function found
9331 // is a non-static member function, pretend as if that was the
9332 // target, it's the only possible type to end up with.
9333 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruth90434232011-03-29 08:08:18 +00009334
David Majnemer576a9af2013-08-01 06:13:59 +00009335 // And skip adding the function if its not in the proper form.
9336 // We'll diagnose this due to an empty set of functions.
9337 if (!OvlExprInfo.HasFormOfMemberPointer)
9338 return;
Chandler Carruth90434232011-03-29 08:08:18 +00009339 }
9340
David Majnemer576a9af2013-08-01 06:13:59 +00009341 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor83314aa2009-07-08 20:55:45 +00009342 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009343 return;
Douglas Gregor83314aa2009-07-08 20:55:45 +00009344 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009345
9346 if (OvlExpr->hasExplicitTemplateArgs())
9347 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00009348
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009349 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9350 // C++ [over.over]p4:
9351 // If more than one function is selected, [...]
9352 if (Matches.size() > 1) {
9353 if (FoundNonTemplateFunction)
9354 EliminateAllTemplateMatches();
9355 else
9356 EliminateAllExceptMostSpecializedTemplate();
9357 }
9358 }
9359 }
9360
9361private:
9362 bool isTargetTypeAFunction() const {
9363 return TargetFunctionType->isFunctionType();
9364 }
9365
9366 // [ToType] [Return]
9367
9368 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9369 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9370 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9371 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9372 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9373 }
9374
9375 // return true if any matching specializations were found
9376 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9377 const DeclAccessPair& CurAccessFunPair) {
9378 if (CXXMethodDecl *Method
9379 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9380 // Skip non-static function templates when converting to pointer, and
9381 // static when converting to member pointer.
9382 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9383 return false;
9384 }
9385 else if (TargetTypeIsNonStaticMemberFunction)
9386 return false;
9387
9388 // C++ [over.over]p2:
9389 // If the name is a function template, template argument deduction is
9390 // done (14.8.2.2), and if the argument deduction succeeds, the
9391 // resulting template argument list is used to generate a single
9392 // function template specialization, which is added to the set of
9393 // overloaded functions considered.
9394 FunctionDecl *Specialization = 0;
Larisse Voufo43847122013-07-19 23:00:19 +00009395 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009396 if (Sema::TemplateDeductionResult Result
9397 = S.DeduceTemplateArguments(FunctionTemplate,
9398 &OvlExplicitTemplateArgs,
9399 TargetFunctionType, Specialization,
Douglas Gregor092140a2013-04-17 08:45:07 +00009400 Info, /*InOverloadResolution=*/true)) {
Larisse Voufo43847122013-07-19 23:00:19 +00009401 // Make a note of the failed deduction for diagnostics.
9402 FailedCandidates.addCandidate()
9403 .set(FunctionTemplate->getTemplatedDecl(),
9404 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009405 return false;
9406 }
9407
Douglas Gregor092140a2013-04-17 08:45:07 +00009408 // Template argument deduction ensures that we have an exact match or
9409 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009410 // This function template specicalization works.
9411 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Douglas Gregor092140a2013-04-17 08:45:07 +00009412 assert(S.isSameOrCompatibleFunctionType(
9413 Context.getCanonicalType(Specialization->getType()),
9414 Context.getCanonicalType(TargetFunctionType)));
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009415 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9416 return true;
9417 }
9418
9419 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9420 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthbd647292009-12-29 06:17:27 +00009421 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00009422 // Skip non-static functions when converting to pointer, and static
9423 // when converting to member pointer.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009424 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9425 return false;
9426 }
9427 else if (TargetTypeIsNonStaticMemberFunction)
9428 return false;
Douglas Gregor904eed32008-11-10 20:40:00 +00009429
Chandler Carruthbd647292009-12-29 06:17:27 +00009430 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009431 if (S.getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00009432 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9433 if (S.CheckCUDATarget(Caller, FunDecl))
9434 return false;
9435
Richard Smith60e141e2013-05-04 07:00:32 +00009436 // If any candidate has a placeholder return type, trigger its deduction
9437 // now.
9438 if (S.getLangOpts().CPlusPlus1y &&
9439 FunDecl->getResultType()->isUndeducedType() &&
9440 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
9441 return false;
9442
Douglas Gregor43c79c22009-12-09 00:47:37 +00009443 QualType ResultTy;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009444 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9445 FunDecl->getType()) ||
Chandler Carruth18e04612011-06-18 01:19:03 +00009446 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9447 ResultTy)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009448 Matches.push_back(std::make_pair(CurAccessFunPair,
9449 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00009450 FoundNonTemplateFunction = true;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009451 return true;
Douglas Gregor00aeb522009-07-08 23:33:52 +00009452 }
Mike Stump1eb44332009-09-09 15:08:12 +00009453 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009454
9455 return false;
9456 }
9457
9458 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9459 bool Ret = false;
9460
9461 // If the overload expression doesn't have the form of a pointer to
9462 // member, don't try to convert it to a pointer-to-member type.
9463 if (IsInvalidFormOfPointerToMemberFunction())
9464 return false;
9465
9466 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9467 E = OvlExpr->decls_end();
9468 I != E; ++I) {
9469 // Look through any using declarations to find the underlying function.
9470 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9471
9472 // C++ [over.over]p3:
9473 // Non-member functions and static member functions match
9474 // targets of type "pointer-to-function" or "reference-to-function."
9475 // Nonstatic member functions match targets of
9476 // type "pointer-to-member-function."
9477 // Note that according to DR 247, the containing class does not matter.
9478 if (FunctionTemplateDecl *FunctionTemplate
9479 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9480 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9481 Ret = true;
9482 }
9483 // If we have explicit template arguments supplied, skip non-templates.
9484 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9485 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9486 Ret = true;
9487 }
9488 assert(Ret || Matches.empty());
9489 return Ret;
Douglas Gregor904eed32008-11-10 20:40:00 +00009490 }
9491
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009492 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00009493 // [...] and any given function template specialization F1 is
9494 // eliminated if the set contains a second function template
9495 // specialization whose function template is more specialized
9496 // than the function template of F1 according to the partial
9497 // ordering rules of 14.5.5.2.
9498
9499 // The algorithm specified above is quadratic. We instead use a
9500 // two-pass algorithm (similar to the one used to identify the
9501 // best viable function in an overload set) that identifies the
9502 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00009503
9504 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9505 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9506 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009507
Larisse Voufo43847122013-07-19 23:00:19 +00009508 // TODO: It looks like FailedCandidates does not serve much purpose
9509 // here, since the no_viable diagnostic has index 0.
9510 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith4ad09e62013-09-10 22:59:25 +00009511 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo43847122013-07-19 23:00:19 +00009512 SourceExpr->getLocStart(), S.PDiag(),
9513 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
9514 .second->getDeclName(),
9515 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
9516 Complain, TargetFunctionType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009517
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009518 if (Result != MatchesCopy.end()) {
9519 // Make it the first and only element
9520 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9521 Matches[0].second = cast<FunctionDecl>(*Result);
9522 Matches.resize(1);
John McCallc373d482010-01-27 01:50:18 +00009523 }
9524 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009525
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009526 void EliminateAllTemplateMatches() {
9527 // [...] any function template specializations in the set are
9528 // eliminated if the set also contains a non-template function, [...]
9529 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9530 if (Matches[I].second->getPrimaryTemplate() == 0)
9531 ++I;
9532 else {
9533 Matches[I] = Matches[--N];
9534 Matches.set_size(N);
9535 }
9536 }
9537 }
9538
9539public:
9540 void ComplainNoMatchesFound() const {
9541 assert(Matches.empty());
9542 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9543 << OvlExpr->getName() << TargetFunctionType
9544 << OvlExpr->getSourceRange();
Richard Smith72a36a12013-08-14 00:00:44 +00009545 if (FailedCandidates.empty())
9546 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9547 else {
9548 // We have some deduction failure messages. Use them to diagnose
9549 // the function templates, and diagnose the non-template candidates
9550 // normally.
9551 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9552 IEnd = OvlExpr->decls_end();
9553 I != IEnd; ++I)
9554 if (FunctionDecl *Fun =
9555 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
9556 S.NoteOverloadCandidate(Fun, TargetFunctionType);
9557 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
9558 }
9559 }
9560
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009561 bool IsInvalidFormOfPointerToMemberFunction() const {
9562 return TargetTypeIsNonStaticMemberFunction &&
9563 !OvlExprInfo.HasFormOfMemberPointer;
9564 }
David Majnemer576a9af2013-08-01 06:13:59 +00009565
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009566 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9567 // TODO: Should we condition this on whether any functions might
9568 // have matched, or is it more appropriate to do that in callers?
9569 // TODO: a fixit wouldn't hurt.
9570 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9571 << TargetType << OvlExpr->getSourceRange();
9572 }
David Majnemer576a9af2013-08-01 06:13:59 +00009573
9574 bool IsStaticMemberFunctionFromBoundPointer() const {
9575 return StaticMemberFunctionFromBoundPointer;
9576 }
9577
9578 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
9579 S.Diag(OvlExpr->getLocStart(),
9580 diag::err_invalid_form_pointer_member_function)
9581 << OvlExpr->getSourceRange();
9582 }
9583
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009584 void ComplainOfInvalidConversion() const {
9585 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9586 << OvlExpr->getName() << TargetType;
9587 }
9588
9589 void ComplainMultipleMatchesFound() const {
9590 assert(Matches.size() > 1);
9591 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9592 << OvlExpr->getName()
9593 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009594 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009595 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009596
9597 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9598
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009599 int getNumMatches() const { return Matches.size(); }
9600
9601 FunctionDecl* getMatchingFunctionDecl() const {
9602 if (Matches.size() != 1) return 0;
9603 return Matches[0].second;
9604 }
9605
9606 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9607 if (Matches.size() != 1) return 0;
9608 return &Matches[0].first;
9609 }
9610};
9611
9612/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9613/// an overloaded function (C++ [over.over]), where @p From is an
9614/// expression with overloaded function type and @p ToType is the type
9615/// we're trying to resolve to. For example:
9616///
9617/// @code
9618/// int f(double);
9619/// int f(int);
9620///
9621/// int (*pfd)(double) = f; // selects f(double)
9622/// @endcode
9623///
9624/// This routine returns the resulting FunctionDecl if it could be
9625/// resolved, and NULL otherwise. When @p Complain is true, this
9626/// routine will emit diagnostics if there is an error.
9627FunctionDecl *
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009628Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9629 QualType TargetType,
9630 bool Complain,
9631 DeclAccessPair &FoundResult,
9632 bool *pHadMultipleCandidates) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009633 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009634
9635 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9636 Complain);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009637 int NumMatches = Resolver.getNumMatches();
9638 FunctionDecl* Fn = 0;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009639 if (NumMatches == 0 && Complain) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009640 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9641 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9642 else
9643 Resolver.ComplainNoMatchesFound();
9644 }
9645 else if (NumMatches > 1 && Complain)
9646 Resolver.ComplainMultipleMatchesFound();
9647 else if (NumMatches == 1) {
9648 Fn = Resolver.getMatchingFunctionDecl();
9649 assert(Fn);
9650 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemer576a9af2013-08-01 06:13:59 +00009651 if (Complain) {
9652 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
9653 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
9654 else
9655 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
9656 }
Sebastian Redl07ab2022009-10-17 21:12:09 +00009657 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009658
9659 if (pHadMultipleCandidates)
9660 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009661 return Fn;
Douglas Gregor904eed32008-11-10 20:40:00 +00009662}
9663
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009664/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor4b52e252009-12-21 23:17:24 +00009665/// resolve that overloaded function expression down to a single function.
9666///
9667/// This routine can only resolve template-ids that refer to a single function
9668/// template, where that template-id refers to a single template whose template
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009669/// arguments are either provided by the template-id or have defaults,
Douglas Gregor4b52e252009-12-21 23:17:24 +00009670/// as described in C++0x [temp.arg.explicit]p3.
John McCall864c0412011-04-26 20:42:42 +00009671FunctionDecl *
9672Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9673 bool Complain,
9674 DeclAccessPair *FoundResult) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009675 // C++ [over.over]p1:
9676 // [...] [Note: any redundant set of parentheses surrounding the
9677 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00009678 // C++ [over.over]p1:
9679 // [...] The overloaded function name can be preceded by the &
9680 // operator.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009681
Douglas Gregor4b52e252009-12-21 23:17:24 +00009682 // If we didn't actually find any template-ids, we're done.
John McCall864c0412011-04-26 20:42:42 +00009683 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00009684 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00009685
9686 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall864c0412011-04-26 20:42:42 +00009687 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Larisse Voufo43847122013-07-19 23:00:19 +00009688 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009689
Douglas Gregor4b52e252009-12-21 23:17:24 +00009690 // Look through all of the overloaded functions, searching for one
9691 // whose type matches exactly.
9692 FunctionDecl *Matched = 0;
John McCall864c0412011-04-26 20:42:42 +00009693 for (UnresolvedSetIterator I = ovl->decls_begin(),
9694 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009695 // C++0x [temp.arg.explicit]p3:
9696 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009697 // where deduction is not done, if a template argument list is
9698 // specified and it, along with any default template arguments,
9699 // identifies a single function template specialization, then the
Douglas Gregor4b52e252009-12-21 23:17:24 +00009700 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00009701 FunctionTemplateDecl *FunctionTemplate
9702 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009703
Douglas Gregor4b52e252009-12-21 23:17:24 +00009704 // C++ [over.over]p2:
9705 // If the name is a function template, template argument deduction is
9706 // done (14.8.2.2), and if the argument deduction succeeds, the
9707 // resulting template argument list is used to generate a single
9708 // function template specialization, which is added to the set of
9709 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00009710 FunctionDecl *Specialization = 0;
Larisse Voufo43847122013-07-19 23:00:19 +00009711 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor4b52e252009-12-21 23:17:24 +00009712 if (TemplateDeductionResult Result
9713 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor092140a2013-04-17 08:45:07 +00009714 Specialization, Info,
9715 /*InOverloadResolution=*/true)) {
Larisse Voufo43847122013-07-19 23:00:19 +00009716 // Make a note of the failed deduction for diagnostics.
9717 // TODO: Actually use the failed-deduction info?
9718 FailedCandidates.addCandidate()
9719 .set(FunctionTemplate->getTemplatedDecl(),
9720 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor4b52e252009-12-21 23:17:24 +00009721 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009722 }
9723
John McCall864c0412011-04-26 20:42:42 +00009724 assert(Specialization && "no specialization and no error?");
9725
Douglas Gregor4b52e252009-12-21 23:17:24 +00009726 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009727 if (Matched) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009728 if (Complain) {
John McCall864c0412011-04-26 20:42:42 +00009729 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9730 << ovl->getName();
9731 NoteAllOverloadCandidates(ovl);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009732 }
Douglas Gregor4b52e252009-12-21 23:17:24 +00009733 return 0;
John McCall864c0412011-04-26 20:42:42 +00009734 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009735
John McCall864c0412011-04-26 20:42:42 +00009736 Matched = Specialization;
9737 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor4b52e252009-12-21 23:17:24 +00009738 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009739
Richard Smith60e141e2013-05-04 07:00:32 +00009740 if (Matched && getLangOpts().CPlusPlus1y &&
9741 Matched->getResultType()->isUndeducedType() &&
9742 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
9743 return 0;
9744
Douglas Gregor4b52e252009-12-21 23:17:24 +00009745 return Matched;
9746}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009747
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009748
9749
9750
John McCall6dbba4f2011-10-11 23:14:30 +00009751// Resolve and fix an overloaded expression that can be resolved
9752// because it identifies a single function template specialization.
9753//
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009754// Last three arguments should only be supplied if Complain = true
John McCall6dbba4f2011-10-11 23:14:30 +00009755//
9756// Return true if it was logically possible to so resolve the
9757// expression, regardless of whether or not it succeeded. Always
9758// returns true if 'complain' is set.
9759bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9760 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9761 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009762 QualType DestTypeForComplaining,
John McCall864c0412011-04-26 20:42:42 +00009763 unsigned DiagIDForComplaining) {
John McCall6dbba4f2011-10-11 23:14:30 +00009764 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009765
John McCall6dbba4f2011-10-11 23:14:30 +00009766 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009767
John McCall864c0412011-04-26 20:42:42 +00009768 DeclAccessPair found;
9769 ExprResult SingleFunctionExpression;
9770 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9771 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009772 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall6dbba4f2011-10-11 23:14:30 +00009773 SrcExpr = ExprError();
9774 return true;
9775 }
John McCall864c0412011-04-26 20:42:42 +00009776
9777 // It is only correct to resolve to an instance method if we're
9778 // resolving a form that's permitted to be a pointer to member.
9779 // Otherwise we'll end up making a bound member expression, which
9780 // is illegal in all the contexts we resolve like this.
9781 if (!ovl.HasFormOfMemberPointer &&
9782 isa<CXXMethodDecl>(fn) &&
9783 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall6dbba4f2011-10-11 23:14:30 +00009784 if (!complain) return false;
9785
9786 Diag(ovl.Expression->getExprLoc(),
9787 diag::err_bound_member_function)
9788 << 0 << ovl.Expression->getSourceRange();
9789
9790 // TODO: I believe we only end up here if there's a mix of
9791 // static and non-static candidates (otherwise the expression
9792 // would have 'bound member' type, not 'overload' type).
9793 // Ideally we would note which candidate was chosen and why
9794 // the static candidates were rejected.
9795 SrcExpr = ExprError();
9796 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009797 }
Douglas Gregordb2eae62011-03-16 19:16:25 +00009798
Sylvestre Ledru43e3dee2012-07-31 06:56:50 +00009799 // Fix the expression to refer to 'fn'.
John McCall864c0412011-04-26 20:42:42 +00009800 SingleFunctionExpression =
John McCall6dbba4f2011-10-11 23:14:30 +00009801 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall864c0412011-04-26 20:42:42 +00009802
9803 // If desired, do function-to-pointer decay.
John McCall6dbba4f2011-10-11 23:14:30 +00009804 if (doFunctionPointerConverion) {
John McCall864c0412011-04-26 20:42:42 +00009805 SingleFunctionExpression =
9806 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall6dbba4f2011-10-11 23:14:30 +00009807 if (SingleFunctionExpression.isInvalid()) {
9808 SrcExpr = ExprError();
9809 return true;
9810 }
9811 }
John McCall864c0412011-04-26 20:42:42 +00009812 }
9813
9814 if (!SingleFunctionExpression.isUsable()) {
9815 if (complain) {
9816 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9817 << ovl.Expression->getName()
9818 << DestTypeForComplaining
9819 << OpRangeForComplaining
9820 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall6dbba4f2011-10-11 23:14:30 +00009821 NoteAllOverloadCandidates(SrcExpr.get());
9822
9823 SrcExpr = ExprError();
9824 return true;
9825 }
9826
9827 return false;
John McCall864c0412011-04-26 20:42:42 +00009828 }
9829
John McCall6dbba4f2011-10-11 23:14:30 +00009830 SrcExpr = SingleFunctionExpression;
9831 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009832}
9833
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009834/// \brief Add a single candidate to the overload set.
9835static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00009836 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00009837 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009838 ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009839 OverloadCandidateSet &CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00009840 bool PartialOverloading,
9841 bool KnownValid) {
John McCall9aa472c2010-03-19 07:35:19 +00009842 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00009843 if (isa<UsingShadowDecl>(Callee))
9844 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9845
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009846 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith2ced0442011-06-26 22:19:54 +00009847 if (ExplicitTemplateArgs) {
9848 assert(!KnownValid && "Explicit template arguments?");
9849 return;
9850 }
Ahmed Charles13a140c2012-02-25 11:00:22 +00009851 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9852 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009853 return;
John McCallba135432009-11-21 08:51:07 +00009854 }
9855
9856 if (FunctionTemplateDecl *FuncTemplate
9857 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00009858 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009859 ExplicitTemplateArgs, Args, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00009860 return;
9861 }
9862
Richard Smith2ced0442011-06-26 22:19:54 +00009863 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009864}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009865
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009866/// \brief Add the overload candidates named by callee and/or found by argument
9867/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00009868void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009869 ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009870 OverloadCandidateSet &CandidateSet,
9871 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00009872
9873#ifndef NDEBUG
9874 // Verify that ArgumentDependentLookup is consistent with the rules
9875 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009876 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009877 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9878 // and let Y be the lookup set produced by argument dependent
9879 // lookup (defined as follows). If X contains
9880 //
9881 // -- a declaration of a class member, or
9882 //
9883 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00009884 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009885 //
9886 // -- a declaration that is neither a function or a function
9887 // template
9888 //
9889 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00009890
John McCall3b4294e2009-12-16 12:17:52 +00009891 if (ULE->requiresADL()) {
9892 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9893 E = ULE->decls_end(); I != E; ++I) {
9894 assert(!(*I)->getDeclContext()->isRecord());
9895 assert(isa<UsingShadowDecl>(*I) ||
9896 !(*I)->getDeclContext()->isFunctionOrMethod());
9897 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00009898 }
9899 }
9900#endif
9901
John McCall3b4294e2009-12-16 12:17:52 +00009902 // It would be nice to avoid this copy.
9903 TemplateArgumentListInfo TABuffer;
Douglas Gregor67714232011-03-03 02:41:12 +00009904 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009905 if (ULE->hasExplicitTemplateArgs()) {
9906 ULE->copyTemplateArgumentsInto(TABuffer);
9907 ExplicitTemplateArgs = &TABuffer;
9908 }
9909
9910 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9911 E = ULE->decls_end(); I != E; ++I)
Ahmed Charles13a140c2012-02-25 11:00:22 +00009912 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9913 CandidateSet, PartialOverloading,
9914 /*KnownValid*/ true);
John McCallba135432009-11-21 08:51:07 +00009915
John McCall3b4294e2009-12-16 12:17:52 +00009916 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00009917 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00009918 ULE->getExprLoc(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009919 Args, ExplicitTemplateArgs,
Richard Smithb1502bc2012-10-18 17:56:02 +00009920 CandidateSet, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009921}
John McCall578b69b2009-12-16 08:11:27 +00009922
Richard Smithd3ff3252013-06-12 22:56:54 +00009923/// Determine whether a declaration with the specified name could be moved into
9924/// a different namespace.
9925static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
9926 switch (Name.getCXXOverloadedOperator()) {
9927 case OO_New: case OO_Array_New:
9928 case OO_Delete: case OO_Array_Delete:
9929 return false;
9930
9931 default:
9932 return true;
9933 }
9934}
9935
Richard Smithf50e88a2011-06-05 22:42:48 +00009936/// Attempt to recover from an ill-formed use of a non-dependent name in a
9937/// template, where the non-dependent name was declared after the template
9938/// was defined. This is common in code written for a compilers which do not
9939/// correctly implement two-stage name lookup.
9940///
9941/// Returns true if a viable candidate was found and a diagnostic was issued.
9942static bool
9943DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9944 const CXXScopeSpec &SS, LookupResult &R,
9945 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009946 ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009947 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9948 return false;
9949
9950 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewycky5a7120c2012-03-14 20:41:00 +00009951 if (DC->isTransparentContext())
9952 continue;
9953
Richard Smithf50e88a2011-06-05 22:42:48 +00009954 SemaRef.LookupQualifiedName(R, DC);
9955
9956 if (!R.empty()) {
9957 R.suppressDiagnostics();
9958
9959 if (isa<CXXRecordDecl>(DC)) {
9960 // Don't diagnose names we find in classes; we get much better
9961 // diagnostics for these from DiagnoseEmptyLookup.
9962 R.clear();
9963 return false;
9964 }
9965
9966 OverloadCandidateSet Candidates(FnLoc);
9967 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9968 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009969 ExplicitTemplateArgs, Args,
Richard Smith2ced0442011-06-26 22:19:54 +00009970 Candidates, false, /*KnownValid*/ false);
Richard Smithf50e88a2011-06-05 22:42:48 +00009971
9972 OverloadCandidateSet::iterator Best;
Richard Smith2ced0442011-06-26 22:19:54 +00009973 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009974 // No viable functions. Don't bother the user with notes for functions
9975 // which don't work and shouldn't be found anyway.
Richard Smith2ced0442011-06-26 22:19:54 +00009976 R.clear();
Richard Smithf50e88a2011-06-05 22:42:48 +00009977 return false;
Richard Smith2ced0442011-06-26 22:19:54 +00009978 }
Richard Smithf50e88a2011-06-05 22:42:48 +00009979
9980 // Find the namespaces where ADL would have looked, and suggest
9981 // declaring the function there instead.
9982 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9983 Sema::AssociatedClassSet AssociatedClasses;
John McCall42f48fb2012-08-24 20:38:34 +00009984 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009985 AssociatedNamespaces,
9986 AssociatedClasses);
Chandler Carruth74d487e2011-06-05 23:36:55 +00009987 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smithd3ff3252013-06-12 22:56:54 +00009988 if (canBeDeclaredInNamespace(R.getLookupName())) {
9989 DeclContext *Std = SemaRef.getStdNamespace();
9990 for (Sema::AssociatedNamespaceSet::iterator
9991 it = AssociatedNamespaces.begin(),
9992 end = AssociatedNamespaces.end(); it != end; ++it) {
9993 // Never suggest declaring a function within namespace 'std'.
9994 if (Std && Std->Encloses(*it))
9995 continue;
Richard Smith19e0d952012-12-22 02:46:14 +00009996
Richard Smithd3ff3252013-06-12 22:56:54 +00009997 // Never suggest declaring a function within a namespace with a
9998 // reserved name, like __gnu_cxx.
9999 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10000 if (NS &&
10001 NS->getQualifiedNameAsString().find("__") != std::string::npos)
10002 continue;
10003
10004 SuggestedNamespaces.insert(*it);
10005 }
Richard Smithf50e88a2011-06-05 22:42:48 +000010006 }
10007
10008 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10009 << R.getLookupName();
Chandler Carruth74d487e2011-06-05 23:36:55 +000010010 if (SuggestedNamespaces.empty()) {
Richard Smithf50e88a2011-06-05 22:42:48 +000010011 SemaRef.Diag(Best->Function->getLocation(),
10012 diag::note_not_found_by_two_phase_lookup)
10013 << R.getLookupName() << 0;
Chandler Carruth74d487e2011-06-05 23:36:55 +000010014 } else if (SuggestedNamespaces.size() == 1) {
Richard Smithf50e88a2011-06-05 22:42:48 +000010015 SemaRef.Diag(Best->Function->getLocation(),
10016 diag::note_not_found_by_two_phase_lookup)
Chandler Carruth74d487e2011-06-05 23:36:55 +000010017 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smithf50e88a2011-06-05 22:42:48 +000010018 } else {
10019 // FIXME: It would be useful to list the associated namespaces here,
10020 // but the diagnostics infrastructure doesn't provide a way to produce
10021 // a localized representation of a list of items.
10022 SemaRef.Diag(Best->Function->getLocation(),
10023 diag::note_not_found_by_two_phase_lookup)
10024 << R.getLookupName() << 2;
10025 }
10026
10027 // Try to recover by calling this function.
10028 return true;
10029 }
10030
10031 R.clear();
10032 }
10033
10034 return false;
10035}
10036
10037/// Attempt to recover from ill-formed use of a non-dependent operator in a
10038/// template, where the non-dependent operator was declared after the template
10039/// was defined.
10040///
10041/// Returns true if a viable candidate was found and a diagnostic was issued.
10042static bool
10043DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10044 SourceLocation OpLoc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010045 ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +000010046 DeclarationName OpName =
10047 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10048 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10049 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010050 /*ExplicitTemplateArgs=*/0, Args);
Richard Smithf50e88a2011-06-05 22:42:48 +000010051}
10052
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +000010053namespace {
Richard Smithe49ff3e2012-09-25 04:46:05 +000010054class BuildRecoveryCallExprRAII {
10055 Sema &SemaRef;
10056public:
10057 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10058 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10059 SemaRef.IsBuildingRecoveryCallExpr = true;
10060 }
10061
10062 ~BuildRecoveryCallExprRAII() {
10063 SemaRef.IsBuildingRecoveryCallExpr = false;
10064 }
10065};
10066
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +000010067}
10068
John McCall578b69b2009-12-16 08:11:27 +000010069/// Attempts to recover from a call where no functions were found.
10070///
10071/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +000010072static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +000010073BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +000010074 UnresolvedLookupExpr *ULE,
10075 SourceLocation LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010076 llvm::MutableArrayRef<Expr *> Args,
Richard Smithf50e88a2011-06-05 22:42:48 +000010077 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +000010078 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smithe49ff3e2012-09-25 04:46:05 +000010079 // Do not try to recover if it is already building a recovery call.
10080 // This stops infinite loops for template instantiations like
10081 //
10082 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10083 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10084 //
10085 if (SemaRef.IsBuildingRecoveryCallExpr)
10086 return ExprError();
10087 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCall578b69b2009-12-16 08:11:27 +000010088
10089 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +000010090 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnarae4b92762012-01-27 09:46:47 +000010091 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCall578b69b2009-12-16 08:11:27 +000010092
John McCall3b4294e2009-12-16 12:17:52 +000010093 TemplateArgumentListInfo TABuffer;
Richard Smithf50e88a2011-06-05 22:42:48 +000010094 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +000010095 if (ULE->hasExplicitTemplateArgs()) {
10096 ULE->copyTemplateArgumentsInto(TABuffer);
10097 ExplicitTemplateArgs = &TABuffer;
10098 }
10099
John McCall578b69b2009-12-16 08:11:27 +000010100 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10101 Sema::LookupOrdinaryName);
Kaelyn Uhrain761695f2013-07-08 23:13:39 +000010102 FunctionCallFilterCCC Validator(SemaRef, Args.size(),
10103 ExplicitTemplateArgs != 0);
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +000010104 NoTypoCorrectionCCC RejectAll;
10105 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
10106 (CorrectionCandidateCallback*)&Validator :
10107 (CorrectionCandidateCallback*)&RejectAll;
Richard Smithf50e88a2011-06-05 22:42:48 +000010108 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010109 ExplicitTemplateArgs, Args) &&
Richard Smithf50e88a2011-06-05 22:42:48 +000010110 (!EmptyLookup ||
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +000010111 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010112 ExplicitTemplateArgs, Args)))
John McCallf312b1e2010-08-26 23:41:50 +000010113 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +000010114
John McCall3b4294e2009-12-16 12:17:52 +000010115 assert(!R.empty() && "lookup results empty despite recovery");
10116
10117 // Build an implicit member call if appropriate. Just drop the
10118 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +000010119 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +000010120 if ((*R.begin())->isCXXClassMember())
Abramo Bagnarae4b92762012-01-27 09:46:47 +000010121 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
10122 R, ExplicitTemplateArgs);
Abramo Bagnara9d9922a2012-02-06 14:31:00 +000010123 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnarae4b92762012-01-27 09:46:47 +000010124 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara9d9922a2012-02-06 14:31:00 +000010125 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +000010126 else
10127 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10128
10129 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +000010130 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +000010131
10132 // This shouldn't cause an infinite loop because we're giving it
Richard Smithf50e88a2011-06-05 22:42:48 +000010133 // an expression with viable lookup results, which should never
John McCall3b4294e2009-12-16 12:17:52 +000010134 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +000010135 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010136 MultiExprArg(Args.data(), Args.size()),
10137 RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +000010138}
Douglas Gregord7a95972010-06-08 17:35:15 +000010139
Sam Panzere1715b62012-08-21 00:52:01 +000010140/// \brief Constructs and populates an OverloadedCandidateSet from
10141/// the given function.
10142/// \returns true when an the ExprResult output parameter has been set.
10143bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10144 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010145 MultiExprArg Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010146 SourceLocation RParenLoc,
10147 OverloadCandidateSet *CandidateSet,
10148 ExprResult *Result) {
John McCall3b4294e2009-12-16 12:17:52 +000010149#ifndef NDEBUG
10150 if (ULE->requiresADL()) {
10151 // To do ADL, we must have found an unqualified name.
10152 assert(!ULE->getQualifier() && "qualified name with ADL");
10153
10154 // We don't perform ADL for implicit declarations of builtins.
10155 // Verify that this was correctly set up.
10156 FunctionDecl *F;
10157 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10158 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10159 F->getBuiltinID() && F->isImplicit())
David Blaikieb219cfc2011-09-23 05:06:16 +000010160 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010161
John McCall3b4294e2009-12-16 12:17:52 +000010162 // We don't perform ADL in C.
David Blaikie4e4d0842012-03-11 07:00:24 +000010163 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb1502bc2012-10-18 17:56:02 +000010164 }
John McCall3b4294e2009-12-16 12:17:52 +000010165#endif
10166
John McCall5acb0c92011-10-17 18:40:02 +000010167 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010168 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzere1715b62012-08-21 00:52:01 +000010169 *Result = ExprError();
10170 return true;
10171 }
Douglas Gregor17330012009-02-04 15:01:18 +000010172
John McCall3b4294e2009-12-16 12:17:52 +000010173 // Add the functions denoted by the callee to the set of candidate
10174 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010175 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +000010176
10177 // If we found nothing, try to recover.
Richard Smithf50e88a2011-06-05 22:42:48 +000010178 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
10179 // out if it fails.
Sam Panzere1715b62012-08-21 00:52:01 +000010180 if (CandidateSet->empty()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +000010181 // In Microsoft mode, if we are inside a template class member function then
10182 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichet0f74d1e2011-09-07 00:14:57 +000010183 // to instantiation time to be able to search into type dependent base
Sebastian Redl14b0c192011-09-24 17:48:00 +000010184 // classes.
David Blaikie4e4d0842012-03-11 07:00:24 +000010185 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetc8ff9152011-11-25 01:10:54 +000010186 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010187 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010188 Context.DependentTy, VK_RValue,
10189 RParenLoc);
Sebastian Redl14b0c192011-09-24 17:48:00 +000010190 CE->setTypeDependent(true);
Sam Panzere1715b62012-08-21 00:52:01 +000010191 *Result = Owned(CE);
10192 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +000010193 }
Sam Panzere1715b62012-08-21 00:52:01 +000010194 return false;
Francois Pichet0f74d1e2011-09-07 00:14:57 +000010195 }
John McCall578b69b2009-12-16 08:11:27 +000010196
John McCall5acb0c92011-10-17 18:40:02 +000010197 UnbridgedCasts.restore();
Sam Panzere1715b62012-08-21 00:52:01 +000010198 return false;
10199}
John McCall5acb0c92011-10-17 18:40:02 +000010200
Sam Panzere1715b62012-08-21 00:52:01 +000010201/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10202/// the completed call expression. If overload resolution fails, emits
10203/// diagnostics and returns ExprError()
10204static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10205 UnresolvedLookupExpr *ULE,
10206 SourceLocation LParenLoc,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010207 MultiExprArg Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010208 SourceLocation RParenLoc,
10209 Expr *ExecConfig,
10210 OverloadCandidateSet *CandidateSet,
10211 OverloadCandidateSet::iterator *Best,
10212 OverloadingResult OverloadResult,
10213 bool AllowTypoCorrection) {
10214 if (CandidateSet->empty())
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010215 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010216 RParenLoc, /*EmptyLookup=*/true,
10217 AllowTypoCorrection);
10218
10219 switch (OverloadResult) {
John McCall3b4294e2009-12-16 12:17:52 +000010220 case OR_Success: {
Sam Panzere1715b62012-08-21 00:52:01 +000010221 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzere1715b62012-08-21 00:52:01 +000010222 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +000010223 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10224 return ExprError();
Sam Panzere1715b62012-08-21 00:52:01 +000010225 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010226 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10227 ExecConfig);
John McCall3b4294e2009-12-16 12:17:52 +000010228 }
Douglas Gregorf6b89692008-11-26 05:54:23 +000010229
Richard Smithf50e88a2011-06-05 22:42:48 +000010230 case OR_No_Viable_Function: {
10231 // Try to recover by looking for viable functions which the user might
10232 // have meant to call.
Sam Panzere1715b62012-08-21 00:52:01 +000010233 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010234 Args, RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +000010235 /*EmptyLookup=*/false,
10236 AllowTypoCorrection);
Richard Smithf50e88a2011-06-05 22:42:48 +000010237 if (!Recovery.isInvalid())
10238 return Recovery;
10239
Sam Panzere1715b62012-08-21 00:52:01 +000010240 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregorf6b89692008-11-26 05:54:23 +000010241 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +000010242 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010243 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregorf6b89692008-11-26 05:54:23 +000010244 break;
Richard Smithf50e88a2011-06-05 22:42:48 +000010245 }
Douglas Gregorf6b89692008-11-26 05:54:23 +000010246
10247 case OR_Ambiguous:
Sam Panzere1715b62012-08-21 00:52:01 +000010248 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +000010249 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010250 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregorf6b89692008-11-26 05:54:23 +000010251 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010252
Sam Panzere1715b62012-08-21 00:52:01 +000010253 case OR_Deleted: {
10254 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10255 << (*Best)->Function->isDeleted()
10256 << ULE->getName()
10257 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10258 << Fn->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010259 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis0d579b62011-11-04 15:58:13 +000010260
Sam Panzere1715b62012-08-21 00:52:01 +000010261 // We emitted an error for the unvailable/deleted function call but keep
10262 // the call in the AST.
10263 FunctionDecl *FDecl = (*Best)->Function;
10264 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010265 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10266 ExecConfig);
Sam Panzere1715b62012-08-21 00:52:01 +000010267 }
Douglas Gregorf6b89692008-11-26 05:54:23 +000010268 }
10269
Douglas Gregorff331c12010-07-25 18:17:45 +000010270 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +000010271 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +000010272}
10273
Sam Panzere1715b62012-08-21 00:52:01 +000010274/// BuildOverloadedCallExpr - Given the call expression that calls Fn
10275/// (which eventually refers to the declaration Func) and the call
10276/// arguments Args/NumArgs, attempt to resolve the function call down
10277/// to a specific function. If overload resolution succeeds, returns
10278/// the call expression produced by overload resolution.
10279/// Otherwise, emits diagnostics and returns ExprError.
10280ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10281 UnresolvedLookupExpr *ULE,
10282 SourceLocation LParenLoc,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010283 MultiExprArg Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010284 SourceLocation RParenLoc,
10285 Expr *ExecConfig,
10286 bool AllowTypoCorrection) {
10287 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
10288 ExprResult result;
10289
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010290 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10291 &result))
Sam Panzere1715b62012-08-21 00:52:01 +000010292 return result;
10293
10294 OverloadCandidateSet::iterator Best;
10295 OverloadingResult OverloadResult =
10296 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10297
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010298 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010299 RParenLoc, ExecConfig, &CandidateSet,
10300 &Best, OverloadResult,
10301 AllowTypoCorrection);
10302}
10303
John McCall6e266892010-01-26 03:27:55 +000010304static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +000010305 return Functions.size() > 1 ||
10306 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10307}
10308
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010309/// \brief Create a unary operation that may resolve to an overloaded
10310/// operator.
10311///
10312/// \param OpLoc The location of the operator itself (e.g., '*').
10313///
10314/// \param OpcIn The UnaryOperator::Opcode that describes this
10315/// operator.
10316///
James Dennett40ae6662012-06-22 08:52:37 +000010317/// \param Fns The set of non-member functions that will be
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010318/// considered by overload resolution. The caller needs to build this
10319/// set based on the context using, e.g.,
10320/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10321/// set should not contain any member functions; those will be added
10322/// by CreateOverloadedUnaryOp().
10323///
James Dennett8da16872012-06-22 10:32:46 +000010324/// \param Input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010325ExprResult
John McCall6e266892010-01-26 03:27:55 +000010326Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10327 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +000010328 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010329 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010330
10331 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10332 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10333 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +000010334 // TODO: provide better source location info.
10335 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010336
John McCall5acb0c92011-10-17 18:40:02 +000010337 if (checkPlaceholderForOverload(*this, Input))
10338 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010339
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010340 Expr *Args[2] = { Input, 0 };
10341 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +000010342
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010343 // For post-increment and post-decrement, add the implicit '0' as
10344 // the second argument, so that we know this is a post-increment or
10345 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +000010346 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010347 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +000010348 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10349 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010350 NumArgs = 2;
10351 }
10352
Richard Smith958ba642013-05-05 15:51:06 +000010353 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10354
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010355 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010356 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +000010357 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010358 Opc,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010359 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010360 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010361 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010362
John McCallc373d482010-01-27 01:50:18 +000010363 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +000010364 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010365 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010366 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010367 /*ADL*/ true, IsOverloaded(Fns),
10368 Fns.begin(), Fns.end());
Richard Smith958ba642013-05-05 15:51:06 +000010369 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, ArgsArray,
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010370 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010371 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +000010372 OpLoc, false));
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010373 }
10374
10375 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010376 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010377
10378 // Add the candidates from the given function set.
Richard Smith958ba642013-05-05 15:51:06 +000010379 AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010380
10381 // Add operator candidates that are member functions.
Richard Smith958ba642013-05-05 15:51:06 +000010382 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010383
John McCall6e266892010-01-26 03:27:55 +000010384 // Add candidates from ADL.
Richard Smith958ba642013-05-05 15:51:06 +000010385 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, OpLoc,
10386 ArgsArray, /*ExplicitTemplateArgs*/ 0,
John McCall6e266892010-01-26 03:27:55 +000010387 CandidateSet);
10388
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010389 // Add builtin operator candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010390 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010391
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010392 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10393
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010394 // Perform overload resolution.
10395 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010396 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010397 case OR_Success: {
10398 // We found a built-in operator or an overloaded operator.
10399 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +000010400
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010401 if (FnDecl) {
10402 // We matched an overloaded operator. Build a call to that
10403 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +000010404
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010405 // Convert the arguments.
10406 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +000010407 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010408
John Wiegley429bb272011-04-08 18:41:53 +000010409 ExprResult InputRes =
10410 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10411 Best->FoundDecl, Method);
10412 if (InputRes.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010413 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010414 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010415 } else {
10416 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010417 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +000010418 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010419 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +000010420 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010421 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +000010422 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +000010423 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010424 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +000010425 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010426 }
10427
John McCallf89e55a2010-11-18 06:31:45 +000010428 // Determine the result type.
10429 QualType ResultTy = FnDecl->getResultType();
10430 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10431 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +000010432
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010433 // Build the actual expression node.
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010434 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010435 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010436 if (FnExpr.isInvalid())
10437 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +000010438
Eli Friedman4c3b8962009-11-18 03:58:17 +000010439 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +000010440 CallExpr *TheCall =
Richard Smith958ba642013-05-05 15:51:06 +000010441 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), ArgsArray,
Lang Hamesbe9af122012-10-02 04:45:10 +000010442 ResultTy, VK, OpLoc, false);
John McCallb697e082010-05-06 18:15:07 +000010443
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010444 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +000010445 FnDecl))
10446 return ExprError();
10447
John McCall9ae2f072010-08-23 23:25:46 +000010448 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010449 } else {
10450 // We matched a built-in operator. Convert the arguments, then
10451 // break out so that we will build the appropriate built-in
10452 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010453 ExprResult InputRes =
10454 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10455 Best->Conversions[0], AA_Passing);
10456 if (InputRes.isInvalid())
10457 return ExprError();
10458 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010459 break;
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010460 }
John Wiegley429bb272011-04-08 18:41:53 +000010461 }
10462
10463 case OR_No_Viable_Function:
Richard Smithf50e88a2011-06-05 22:42:48 +000010464 // This is an erroneous use of an operator which can be overloaded by
10465 // a non-member function. Check for non-member operators which were
10466 // defined too late to be candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010467 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smithf50e88a2011-06-05 22:42:48 +000010468 // FIXME: Recover by calling the found function.
10469 return ExprError();
10470
John Wiegley429bb272011-04-08 18:41:53 +000010471 // No viable function; fall through to handling this as a
10472 // built-in operator, which will produce an error message for us.
10473 break;
10474
10475 case OR_Ambiguous:
10476 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10477 << UnaryOperator::getOpcodeStr(Opc)
10478 << Input->getType()
10479 << Input->getSourceRange();
Richard Smith958ba642013-05-05 15:51:06 +000010480 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley429bb272011-04-08 18:41:53 +000010481 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10482 return ExprError();
10483
10484 case OR_Deleted:
10485 Diag(OpLoc, diag::err_ovl_deleted_oper)
10486 << Best->Function->isDeleted()
10487 << UnaryOperator::getOpcodeStr(Opc)
10488 << getDeletedOrUnavailableSuffix(Best->Function)
10489 << Input->getSourceRange();
Richard Smith958ba642013-05-05 15:51:06 +000010490 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman1795d372011-08-26 19:46:22 +000010491 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010492 return ExprError();
10493 }
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010494
10495 // Either we found no viable overloaded operator or we matched a
10496 // built-in operator. In either case, fall through to trying to
10497 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +000010498 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010499}
10500
Douglas Gregor063daf62009-03-13 18:40:31 +000010501/// \brief Create a binary operation that may resolve to an overloaded
10502/// operator.
10503///
10504/// \param OpLoc The location of the operator itself (e.g., '+').
10505///
10506/// \param OpcIn The BinaryOperator::Opcode that describes this
10507/// operator.
10508///
James Dennett40ae6662012-06-22 08:52:37 +000010509/// \param Fns The set of non-member functions that will be
Douglas Gregor063daf62009-03-13 18:40:31 +000010510/// considered by overload resolution. The caller needs to build this
10511/// set based on the context using, e.g.,
10512/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10513/// set should not contain any member functions; those will be added
10514/// by CreateOverloadedBinOp().
10515///
10516/// \param LHS Left-hand argument.
10517/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010518ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +000010519Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +000010520 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +000010521 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +000010522 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +000010523 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010524 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +000010525
10526 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10527 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10528 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10529
10530 // If either side is type-dependent, create an appropriate dependent
10531 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010532 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +000010533 if (Fns.empty()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010534 // If there are no functions to store, just build a dependent
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010535 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +000010536 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010537 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +000010538 Context.DependentTy,
10539 VK_RValue, OK_Ordinary,
Lang Hamesbe9af122012-10-02 04:45:10 +000010540 OpLoc,
10541 FPFeatures.fp_contract));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010542
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010543 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10544 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010545 VK_LValue,
10546 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010547 Context.DependentTy,
10548 Context.DependentTy,
Lang Hamesbe9af122012-10-02 04:45:10 +000010549 OpLoc,
10550 FPFeatures.fp_contract));
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010551 }
John McCall6e266892010-01-26 03:27:55 +000010552
10553 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +000010554 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010555 // TODO: provide better source location info in DNLoc component.
10556 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +000010557 UnresolvedLookupExpr *Fn
Douglas Gregor4c9be892011-02-28 20:01:57 +000010558 = UnresolvedLookupExpr::Create(Context, NamingClass,
10559 NestedNameSpecifierLoc(), OpNameInfo,
10560 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010561 Fns.begin(), Fns.end());
Lang Hamesbe9af122012-10-02 04:45:10 +000010562 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10563 Context.DependentTy, VK_RValue,
10564 OpLoc, FPFeatures.fp_contract));
Douglas Gregor063daf62009-03-13 18:40:31 +000010565 }
10566
John McCall5acb0c92011-10-17 18:40:02 +000010567 // Always do placeholder-like conversions on the RHS.
10568 if (checkPlaceholderForOverload(*this, Args[1]))
10569 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010570
John McCall3c3b7f92011-10-25 17:37:35 +000010571 // Do placeholder-like conversion on the LHS; note that we should
10572 // not get here with a PseudoObject LHS.
10573 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall5acb0c92011-10-17 18:40:02 +000010574 if (checkPlaceholderForOverload(*this, Args[0]))
10575 return ExprError();
10576
Sebastian Redl275c2b42009-11-18 23:10:33 +000010577 // If this is the assignment operator, we only perform overload resolution
10578 // if the left-hand side is a class or enumeration type. This is actually
10579 // a hack. The standard requires that we do overload resolution between the
10580 // various built-in candidates, but as DR507 points out, this can lead to
10581 // problems. So we do it this way, which pretty much follows what GCC does.
10582 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +000010583 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010584 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010585
John McCall0e800c92010-12-04 08:14:53 +000010586 // If this is the .* operator, which is not overloadable, just
10587 // create a built-in binary operator.
10588 if (Opc == BO_PtrMemD)
10589 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10590
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010591 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010592 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010593
10594 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010595 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +000010596
10597 // Add operator candidates that are member functions.
Richard Smith958ba642013-05-05 15:51:06 +000010598 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +000010599
John McCall6e266892010-01-26 03:27:55 +000010600 // Add candidates from ADL.
10601 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010602 OpLoc, Args,
John McCall6e266892010-01-26 03:27:55 +000010603 /*ExplicitTemplateArgs*/ 0,
10604 CandidateSet);
10605
Douglas Gregor063daf62009-03-13 18:40:31 +000010606 // Add builtin operator candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010607 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +000010608
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010609 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10610
Douglas Gregor063daf62009-03-13 18:40:31 +000010611 // Perform overload resolution.
10612 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010613 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +000010614 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +000010615 // We found a built-in operator or an overloaded operator.
10616 FunctionDecl *FnDecl = Best->Function;
10617
10618 if (FnDecl) {
10619 // We matched an overloaded operator. Build a call to that
10620 // operator.
10621
10622 // Convert the arguments.
10623 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +000010624 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +000010625 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010626
Chandler Carruth6df868e2010-12-12 08:17:55 +000010627 ExprResult Arg1 =
10628 PerformCopyInitialization(
10629 InitializedEntity::InitializeParameter(Context,
10630 FnDecl->getParamDecl(0)),
10631 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010632 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010633 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010634
John Wiegley429bb272011-04-08 18:41:53 +000010635 ExprResult Arg0 =
10636 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10637 Best->FoundDecl, Method);
10638 if (Arg0.isInvalid())
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010639 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010640 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010641 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010642 } else {
10643 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +000010644 ExprResult Arg0 = PerformCopyInitialization(
10645 InitializedEntity::InitializeParameter(Context,
10646 FnDecl->getParamDecl(0)),
10647 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010648 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010649 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010650
Chandler Carruth6df868e2010-12-12 08:17:55 +000010651 ExprResult Arg1 =
10652 PerformCopyInitialization(
10653 InitializedEntity::InitializeParameter(Context,
10654 FnDecl->getParamDecl(1)),
10655 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010656 if (Arg1.isInvalid())
10657 return ExprError();
10658 Args[0] = LHS = Arg0.takeAs<Expr>();
10659 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010660 }
10661
John McCallf89e55a2010-11-18 06:31:45 +000010662 // Determine the result type.
10663 QualType ResultTy = FnDecl->getResultType();
10664 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10665 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +000010666
10667 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010668 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010669 Best->FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010670 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010671 if (FnExpr.isInvalid())
10672 return ExprError();
Douglas Gregor063daf62009-03-13 18:40:31 +000010673
John McCall9ae2f072010-08-23 23:25:46 +000010674 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010675 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000010676 Args, ResultTy, VK, OpLoc,
10677 FPFeatures.fp_contract);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010678
10679 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000010680 FnDecl))
10681 return ExprError();
10682
Nick Lewycky9b7ea0d2013-01-24 02:03:08 +000010683 ArrayRef<const Expr *> ArgsArray(Args, 2);
10684 // Cut off the implicit 'this'.
10685 if (isa<CXXMethodDecl>(FnDecl))
10686 ArgsArray = ArgsArray.slice(1);
10687 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
10688 TheCall->getSourceRange(), VariadicDoesNotApply);
10689
John McCall9ae2f072010-08-23 23:25:46 +000010690 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +000010691 } else {
10692 // We matched a built-in operator. Convert the arguments, then
10693 // break out so that we will build the appropriate built-in
10694 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010695 ExprResult ArgsRes0 =
10696 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10697 Best->Conversions[0], AA_Passing);
10698 if (ArgsRes0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010699 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010700 Args[0] = ArgsRes0.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010701
John Wiegley429bb272011-04-08 18:41:53 +000010702 ExprResult ArgsRes1 =
10703 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10704 Best->Conversions[1], AA_Passing);
10705 if (ArgsRes1.isInvalid())
10706 return ExprError();
10707 Args[1] = ArgsRes1.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010708 break;
10709 }
10710 }
10711
Douglas Gregor33074752009-09-30 21:46:01 +000010712 case OR_No_Viable_Function: {
10713 // C++ [over.match.oper]p9:
10714 // If the operator is the operator , [...] and there are no
10715 // viable functions, then the operator is assumed to be the
10716 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +000010717 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +000010718 break;
10719
Chandler Carruth6df868e2010-12-12 08:17:55 +000010720 // For class as left operand for assignment or compound assigment
10721 // operator do not fall through to handling in built-in, but report that
10722 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +000010723 ExprResult Result = ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010724 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +000010725 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +000010726 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10727 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010728 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedman3f93d4c2013-08-28 20:35:35 +000010729 if (Args[0]->getType()->isIncompleteType()) {
10730 Diag(OpLoc, diag::note_assign_lhs_incomplete)
10731 << Args[0]->getType()
10732 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10733 }
Douglas Gregor33074752009-09-30 21:46:01 +000010734 } else {
Richard Smithf50e88a2011-06-05 22:42:48 +000010735 // This is an erroneous use of an operator which can be overloaded by
10736 // a non-member function. Check for non-member operators which were
10737 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010738 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smithf50e88a2011-06-05 22:42:48 +000010739 // FIXME: Recover by calling the found function.
10740 return ExprError();
10741
Douglas Gregor33074752009-09-30 21:46:01 +000010742 // No viable function; try to create a built-in operation, which will
10743 // produce an error. Then, show the non-viable candidates.
10744 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +000010745 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010746 assert(Result.isInvalid() &&
Douglas Gregor33074752009-09-30 21:46:01 +000010747 "C++ binary operator overloading is missing candidates!");
10748 if (Result.isInvalid())
Ahmed Charles13a140c2012-02-25 11:00:22 +000010749 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010750 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010751 return Result;
Douglas Gregor33074752009-09-30 21:46:01 +000010752 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010753
10754 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010755 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +000010756 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +000010757 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010758 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010759 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010760 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010761 return ExprError();
10762
10763 case OR_Deleted:
Douglas Gregore4e68d42012-02-15 19:33:52 +000010764 if (isImplicitlyDeleted(Best->Function)) {
10765 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10766 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smith0f46e642012-12-28 12:23:24 +000010767 << Context.getRecordType(Method->getParent())
10768 << getSpecialMember(Method);
Richard Smith5bdaac52012-04-02 20:59:25 +000010769
Richard Smith0f46e642012-12-28 12:23:24 +000010770 // The user probably meant to call this special member. Just
10771 // explain why it's deleted.
10772 NoteDeletedFunction(Method);
10773 return ExprError();
Douglas Gregore4e68d42012-02-15 19:33:52 +000010774 } else {
10775 Diag(OpLoc, diag::err_ovl_deleted_oper)
10776 << Best->Function->isDeleted()
10777 << BinaryOperator::getOpcodeStr(Opc)
10778 << getDeletedOrUnavailableSuffix(Best->Function)
10779 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10780 }
Ahmed Charles13a140c2012-02-25 11:00:22 +000010781 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman1795d372011-08-26 19:46:22 +000010782 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010783 return ExprError();
John McCall1d318332010-01-12 00:44:57 +000010784 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010785
Douglas Gregor33074752009-09-30 21:46:01 +000010786 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010787 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010788}
10789
John McCall60d7b3a2010-08-24 06:29:42 +000010790ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +000010791Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10792 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010793 Expr *Base, Expr *Idx) {
10794 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +000010795 DeclarationName OpName =
10796 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10797
10798 // If either side is type-dependent, create an appropriate dependent
10799 // expression.
10800 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10801
John McCallc373d482010-01-27 01:50:18 +000010802 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010803 // CHECKME: no 'operator' keyword?
10804 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10805 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +000010806 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010807 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010808 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010809 /*ADL*/ true, /*Overloaded*/ false,
10810 UnresolvedSetIterator(),
10811 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +000010812 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +000010813
Sebastian Redlf322ed62009-10-29 20:17:01 +000010814 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010815 Args,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010816 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010817 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +000010818 RLoc, false));
Sebastian Redlf322ed62009-10-29 20:17:01 +000010819 }
10820
John McCall5acb0c92011-10-17 18:40:02 +000010821 // Handle placeholders on both operands.
10822 if (checkPlaceholderForOverload(*this, Args[0]))
10823 return ExprError();
10824 if (checkPlaceholderForOverload(*this, Args[1]))
10825 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010826
Sebastian Redlf322ed62009-10-29 20:17:01 +000010827 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010828 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010829
10830 // Subscript can only be overloaded as a member function.
10831
10832 // Add operator candidates that are member functions.
Richard Smith958ba642013-05-05 15:51:06 +000010833 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010834
10835 // Add builtin operator candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010836 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010837
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010838 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10839
Sebastian Redlf322ed62009-10-29 20:17:01 +000010840 // Perform overload resolution.
10841 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010842 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +000010843 case OR_Success: {
10844 // We found a built-in operator or an overloaded operator.
10845 FunctionDecl *FnDecl = Best->Function;
10846
10847 if (FnDecl) {
10848 // We matched an overloaded operator. Build a call to that
10849 // operator.
10850
John McCall9aa472c2010-03-19 07:35:19 +000010851 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallc373d482010-01-27 01:50:18 +000010852
Sebastian Redlf322ed62009-10-29 20:17:01 +000010853 // Convert the arguments.
10854 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley429bb272011-04-08 18:41:53 +000010855 ExprResult Arg0 =
10856 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10857 Best->FoundDecl, Method);
10858 if (Arg0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010859 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010860 Args[0] = Arg0.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010861
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010862 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010863 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010864 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010865 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010866 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010867 SourceLocation(),
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010868 Owned(Args[1]));
10869 if (InputInit.isInvalid())
10870 return ExprError();
10871
10872 Args[1] = InputInit.takeAs<Expr>();
10873
Sebastian Redlf322ed62009-10-29 20:17:01 +000010874 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +000010875 QualType ResultTy = FnDecl->getResultType();
10876 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10877 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010878
10879 // Build the actual expression node.
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010880 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10881 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010882 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010883 Best->FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010884 HadMultipleCandidates,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010885 OpLocInfo.getLoc(),
10886 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010887 if (FnExpr.isInvalid())
10888 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010889
John McCall9ae2f072010-08-23 23:25:46 +000010890 CXXOperatorCallExpr *TheCall =
10891 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010892 FnExpr.take(), Args,
Lang Hamesbe9af122012-10-02 04:45:10 +000010893 ResultTy, VK, RLoc,
10894 false);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010895
John McCall9ae2f072010-08-23 23:25:46 +000010896 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010897 FnDecl))
10898 return ExprError();
10899
John McCall9ae2f072010-08-23 23:25:46 +000010900 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010901 } else {
10902 // We matched a built-in operator. Convert the arguments, then
10903 // break out so that we will build the appropriate built-in
10904 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010905 ExprResult ArgsRes0 =
10906 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10907 Best->Conversions[0], AA_Passing);
10908 if (ArgsRes0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010909 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010910 Args[0] = ArgsRes0.take();
10911
10912 ExprResult ArgsRes1 =
10913 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10914 Best->Conversions[1], AA_Passing);
10915 if (ArgsRes1.isInvalid())
10916 return ExprError();
10917 Args[1] = ArgsRes1.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010918
10919 break;
10920 }
10921 }
10922
10923 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +000010924 if (CandidateSet.empty())
10925 Diag(LLoc, diag::err_ovl_no_oper)
10926 << Args[0]->getType() << /*subscript*/ 0
10927 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10928 else
10929 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10930 << Args[0]->getType()
10931 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010932 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010933 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +000010934 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010935 }
10936
10937 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010938 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010939 << "[]"
Douglas Gregorae2cf762010-11-13 20:06:38 +000010940 << Args[0]->getType() << Args[1]->getType()
10941 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010942 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010943 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010944 return ExprError();
10945
10946 case OR_Deleted:
10947 Diag(LLoc, diag::err_ovl_deleted_oper)
10948 << Best->Function->isDeleted() << "[]"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010949 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redlf322ed62009-10-29 20:17:01 +000010950 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010951 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010952 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010953 return ExprError();
10954 }
10955
10956 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +000010957 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010958}
10959
Douglas Gregor88a35142008-12-22 05:46:06 +000010960/// BuildCallToMemberFunction - Build a call to a member
10961/// function. MemExpr is the expression that refers to the member
10962/// function (and includes the object parameter), Args/NumArgs are the
10963/// arguments to the function call (not including the object
10964/// parameter). The caller needs to validate that the member
John McCall864c0412011-04-26 20:42:42 +000010965/// expression refers to a non-static member function or an overloaded
10966/// member function.
John McCall60d7b3a2010-08-24 06:29:42 +000010967ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +000010968Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010969 SourceLocation LParenLoc,
10970 MultiExprArg Args,
10971 SourceLocation RParenLoc) {
John McCall864c0412011-04-26 20:42:42 +000010972 assert(MemExprE->getType() == Context.BoundMemberTy ||
10973 MemExprE->getType() == Context.OverloadTy);
10974
Douglas Gregor88a35142008-12-22 05:46:06 +000010975 // Dig out the member expression. This holds both the object
10976 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +000010977 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010978
John McCall864c0412011-04-26 20:42:42 +000010979 // Determine whether this is a call to a pointer-to-member function.
10980 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10981 assert(op->getType() == Context.BoundMemberTy);
10982 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10983
10984 QualType fnType =
10985 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10986
10987 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10988 QualType resultType = proto->getCallResultType(Context);
10989 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10990
10991 // Check that the object type isn't more qualified than the
10992 // member function we're calling.
10993 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10994
10995 QualType objectType = op->getLHS()->getType();
10996 if (op->getOpcode() == BO_PtrMemI)
10997 objectType = objectType->castAs<PointerType>()->getPointeeType();
10998 Qualifiers objectQuals = objectType.getQualifiers();
10999
11000 Qualifiers difference = objectQuals - funcQuals;
11001 difference.removeObjCGCAttr();
11002 difference.removeAddressSpace();
11003 if (difference) {
11004 std::string qualsString = difference.getAsString();
11005 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11006 << fnType.getUnqualifiedType()
11007 << qualsString
11008 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11009 }
11010
11011 CXXMemberCallExpr *call
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011012 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall864c0412011-04-26 20:42:42 +000011013 resultType, valueKind, RParenLoc);
11014
11015 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +000011016 op->getRHS()->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +000011017 call, 0))
11018 return ExprError();
11019
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011020 if (ConvertArgumentsForCall(call, op, 0, proto, Args, RParenLoc))
John McCall864c0412011-04-26 20:42:42 +000011021 return ExprError();
11022
Richard Trieue2a90b82013-06-22 02:30:38 +000011023 if (CheckOtherCall(call, proto))
11024 return ExprError();
11025
John McCall864c0412011-04-26 20:42:42 +000011026 return MaybeBindToTemporary(call);
11027 }
11028
John McCall5acb0c92011-10-17 18:40:02 +000011029 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011030 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall5acb0c92011-10-17 18:40:02 +000011031 return ExprError();
11032
John McCall129e2df2009-11-30 22:42:35 +000011033 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +000011034 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +000011035 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +000011036 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +000011037 if (isa<MemberExpr>(NakedMemExpr)) {
11038 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +000011039 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +000011040 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +000011041 Qualifier = MemExpr->getQualifier();
John McCall5acb0c92011-10-17 18:40:02 +000011042 UnbridgedCasts.restore();
John McCall129e2df2009-11-30 22:42:35 +000011043 } else {
11044 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +000011045 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011046
John McCall701c89e2009-12-03 04:06:58 +000011047 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011048 Expr::Classification ObjectClassification
11049 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11050 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +000011051
Douglas Gregor88a35142008-12-22 05:46:06 +000011052 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +000011053 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +000011054
John McCallaa81e162009-12-01 22:10:20 +000011055 // FIXME: avoid copy.
11056 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11057 if (UnresExpr->hasExplicitTemplateArgs()) {
11058 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11059 TemplateArgs = &TemplateArgsBuffer;
11060 }
11061
John McCall129e2df2009-11-30 22:42:35 +000011062 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11063 E = UnresExpr->decls_end(); I != E; ++I) {
11064
John McCall701c89e2009-12-03 04:06:58 +000011065 NamedDecl *Func = *I;
11066 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11067 if (isa<UsingShadowDecl>(Func))
11068 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11069
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011070
Francois Pichetdbee3412011-01-18 05:04:39 +000011071 // Microsoft supports direct constructor calls.
David Blaikie4e4d0842012-03-11 07:00:24 +000011072 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charles13a140c2012-02-25 11:00:22 +000011073 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011074 Args, CandidateSet);
Francois Pichetdbee3412011-01-18 05:04:39 +000011075 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000011076 // If explicit template arguments were provided, we can't call a
11077 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +000011078 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000011079 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011080
John McCall9aa472c2010-03-19 07:35:19 +000011081 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011082 ObjectClassification, Args, CandidateSet,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011083 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000011084 } else {
John McCall129e2df2009-11-30 22:42:35 +000011085 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +000011086 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011087 ObjectType, ObjectClassification,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011088 Args, CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +000011089 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000011090 }
Douglas Gregordec06662009-08-21 18:42:58 +000011091 }
Mike Stump1eb44332009-09-09 15:08:12 +000011092
John McCall129e2df2009-11-30 22:42:35 +000011093 DeclarationName DeclName = UnresExpr->getMemberName();
11094
John McCall5acb0c92011-10-17 18:40:02 +000011095 UnbridgedCasts.restore();
11096
Douglas Gregor88a35142008-12-22 05:46:06 +000011097 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000011098 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +000011099 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +000011100 case OR_Success:
11101 Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +000011102 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +000011103 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +000011104 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11105 return ExprError();
Faisal Valid570a922013-06-15 11:54:37 +000011106 // If FoundDecl is different from Method (such as if one is a template
11107 // and the other a specialization), make sure DiagnoseUseOfDecl is
11108 // called on both.
11109 // FIXME: This would be more comprehensively addressed by modifying
11110 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11111 // being used.
11112 if (Method != FoundDecl.getDecl() &&
11113 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11114 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000011115 break;
11116
11117 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +000011118 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +000011119 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000011120 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011121 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor88a35142008-12-22 05:46:06 +000011122 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000011123 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000011124
11125 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +000011126 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000011127 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011128 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor88a35142008-12-22 05:46:06 +000011129 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000011130 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011131
11132 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +000011133 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011134 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011135 << DeclName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011136 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011137 << MemExprE->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011138 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011139 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000011140 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000011141 }
11142
John McCall6bb80172010-03-30 21:47:33 +000011143 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +000011144
John McCallaa81e162009-12-01 22:10:20 +000011145 // If overload resolution picked a static member, build a
11146 // non-member call based on that function.
11147 if (Method->isStatic()) {
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011148 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11149 RParenLoc);
John McCallaa81e162009-12-01 22:10:20 +000011150 }
11151
John McCall129e2df2009-11-30 22:42:35 +000011152 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +000011153 }
11154
John McCallf89e55a2010-11-18 06:31:45 +000011155 QualType ResultType = Method->getResultType();
11156 ExprValueKind VK = Expr::getValueKindForType(ResultType);
11157 ResultType = ResultType.getNonLValueExprType(Context);
11158
Douglas Gregor88a35142008-12-22 05:46:06 +000011159 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011160 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011161 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCallf89e55a2010-11-18 06:31:45 +000011162 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +000011163
Anders Carlssoneed3e692009-10-10 00:06:20 +000011164 // Check for a valid return type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011165 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +000011166 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +000011167 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011168
Douglas Gregor88a35142008-12-22 05:46:06 +000011169 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +000011170 // We only need to do this if there was actually an overload; otherwise
11171 // it was done at lookup.
John Wiegley429bb272011-04-08 18:41:53 +000011172 if (!Method->isStatic()) {
11173 ExprResult ObjectArg =
11174 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11175 FoundDecl, Method);
11176 if (ObjectArg.isInvalid())
11177 return ExprError();
11178 MemExpr->setBase(ObjectArg.take());
11179 }
Douglas Gregor88a35142008-12-22 05:46:06 +000011180
11181 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +000011182 const FunctionProtoType *Proto =
11183 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011184 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor88a35142008-12-22 05:46:06 +000011185 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +000011186 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000011187
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011188 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmane61eb042012-02-18 04:48:30 +000011189
Richard Smith831421f2012-06-25 20:30:08 +000011190 if (CheckFunctionCall(Method, TheCall, Proto))
John McCallaa81e162009-12-01 22:10:20 +000011191 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +000011192
Anders Carlsson2174d4c2011-05-06 14:25:31 +000011193 if ((isa<CXXConstructorDecl>(CurContext) ||
11194 isa<CXXDestructorDecl>(CurContext)) &&
11195 TheCall->getMethodDecl()->isPure()) {
11196 const CXXMethodDecl *MD = TheCall->getMethodDecl();
11197
Chandler Carruthae198062011-06-27 08:31:58 +000011198 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson2174d4c2011-05-06 14:25:31 +000011199 Diag(MemExpr->getLocStart(),
11200 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11201 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11202 << MD->getParent()->getDeclName();
11203
11204 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruthae198062011-06-27 08:31:58 +000011205 }
Anders Carlsson2174d4c2011-05-06 14:25:31 +000011206 }
John McCall9ae2f072010-08-23 23:25:46 +000011207 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +000011208}
11209
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011210/// BuildCallToObjectOfClassType - Build a call to an object of class
11211/// type (C++ [over.call.object]), which can end up invoking an
11212/// overloaded function call operator (@c operator()) or performing a
11213/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +000011214ExprResult
John Wiegley429bb272011-04-08 18:41:53 +000011215Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregor5c37de72008-12-06 00:22:45 +000011216 SourceLocation LParenLoc,
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011217 MultiExprArg Args,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011218 SourceLocation RParenLoc) {
John McCall5acb0c92011-10-17 18:40:02 +000011219 if (checkPlaceholderForOverload(*this, Obj))
11220 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011221 ExprResult Object = Owned(Obj);
John McCall5acb0c92011-10-17 18:40:02 +000011222
11223 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011224 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall5acb0c92011-10-17 18:40:02 +000011225 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000011226
John Wiegley429bb272011-04-08 18:41:53 +000011227 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
11228 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +000011229
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011230 // C++ [over.call.object]p1:
11231 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +000011232 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011233 // candidate functions includes at least the function call
11234 // operators of T. The function call operators of T are obtained by
11235 // ordinary lookup of the name operator() in the context of
11236 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +000011237 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +000011238 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +000011239
John Wiegley429bb272011-04-08 18:41:53 +000011240 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000011241 diag::err_incomplete_object_call, Object.get()))
Douglas Gregor593564b2009-11-15 07:48:03 +000011242 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011243
John McCalla24dc2e2009-11-17 02:14:36 +000011244 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11245 LookupQualifiedName(R, Record->getDecl());
11246 R.suppressDiagnostics();
11247
Douglas Gregor593564b2009-11-15 07:48:03 +000011248 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +000011249 Oper != OperEnd; ++Oper) {
John Wiegley429bb272011-04-08 18:41:53 +000011250 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011251 Object.get()->Classify(Context),
11252 Args, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +000011253 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +000011254 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011255
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011256 // C++ [over.call.object]p2:
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011257 // In addition, for each (non-explicit in C++0x) conversion function
11258 // declared in T of the form
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011259 //
11260 // operator conversion-type-id () cv-qualifier;
11261 //
11262 // where cv-qualifier is the same cv-qualification as, or a
11263 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +000011264 // denotes the type "pointer to function of (P1,...,Pn) returning
11265 // R", or the type "reference to pointer to function of
11266 // (P1,...,Pn) returning R", or the type "reference to function
11267 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011268 // is also considered as a candidate function. Similarly,
11269 // surrogate call functions are added to the set of candidate
11270 // functions for each conversion function declared in an
11271 // accessible base class provided the function is not hidden
11272 // within T by another intervening declaration.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000011273 std::pair<CXXRecordDecl::conversion_iterator,
11274 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregor90073282010-01-11 19:36:35 +000011275 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000011276 for (CXXRecordDecl::conversion_iterator
11277 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +000011278 NamedDecl *D = *I;
11279 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11280 if (isa<UsingShadowDecl>(D))
11281 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011282
Douglas Gregor4a27d702009-10-21 06:18:39 +000011283 // Skip over templated conversion functions; they aren't
11284 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +000011285 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +000011286 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +000011287
John McCall701c89e2009-12-03 04:06:58 +000011288 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011289 if (!Conv->isExplicit()) {
11290 // Strip the reference type (if any) and then the pointer type (if
11291 // any) to get down to what might be a function type.
11292 QualType ConvType = Conv->getConversionType().getNonReferenceType();
11293 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11294 ConvType = ConvPtrType->getPointeeType();
John McCallba135432009-11-21 08:51:07 +000011295
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011296 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11297 {
11298 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011299 Object.get(), Args, CandidateSet);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011300 }
11301 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011302 }
Mike Stump1eb44332009-09-09 15:08:12 +000011303
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011304 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11305
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011306 // Perform overload resolution.
11307 OverloadCandidateSet::iterator Best;
John Wiegley429bb272011-04-08 18:41:53 +000011308 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall120d63c2010-08-24 20:38:10 +000011309 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011310 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011311 // Overload resolution succeeded; we'll build the appropriate call
11312 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011313 break;
11314
11315 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +000011316 if (CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +000011317 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley429bb272011-04-08 18:41:53 +000011318 << Object.get()->getType() << /*call*/ 1
11319 << Object.get()->getSourceRange();
John McCall1eb3e102010-01-07 02:04:15 +000011320 else
Daniel Dunbar96a00142012-03-09 18:35:03 +000011321 Diag(Object.get()->getLocStart(),
John McCall1eb3e102010-01-07 02:04:15 +000011322 diag::err_ovl_no_viable_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000011323 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011324 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011325 break;
11326
11327 case OR_Ambiguous:
Daniel Dunbar96a00142012-03-09 18:35:03 +000011328 Diag(Object.get()->getLocStart(),
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011329 diag::err_ovl_ambiguous_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000011330 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011331 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011332 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011333
11334 case OR_Deleted:
Daniel Dunbar96a00142012-03-09 18:35:03 +000011335 Diag(Object.get()->getLocStart(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011336 diag::err_ovl_deleted_object_call)
11337 << Best->Function->isDeleted()
John Wiegley429bb272011-04-08 18:41:53 +000011338 << Object.get()->getType()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011339 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley429bb272011-04-08 18:41:53 +000011340 << Object.get()->getSourceRange();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011341 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011342 break;
Mike Stump1eb44332009-09-09 15:08:12 +000011343 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011344
Douglas Gregorff331c12010-07-25 18:17:45 +000011345 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011346 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011347
John McCall5acb0c92011-10-17 18:40:02 +000011348 UnbridgedCasts.restore();
11349
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011350 if (Best->Function == 0) {
11351 // Since there is no function declaration, this is one of the
11352 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +000011353 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011354 = cast<CXXConversionDecl>(
11355 Best->Conversions[0].UserDefined.ConversionFunction);
11356
John Wiegley429bb272011-04-08 18:41:53 +000011357 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +000011358 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11359 return ExprError();
Faisal Valid570a922013-06-15 11:54:37 +000011360 assert(Conv == Best->FoundDecl.getDecl() &&
11361 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011362 // We selected one of the surrogate functions that converts the
11363 // object parameter to a function pointer. Perform the conversion
11364 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011365
Fariborz Jahaniand8307b12009-09-28 18:35:46 +000011366 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +000011367 // and then call it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011368 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11369 Conv, HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +000011370 if (Call.isInvalid())
11371 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +000011372 // Record usage of conversion in an implicit cast.
11373 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
11374 CK_UserDefinedConversion,
11375 Call.get(), 0, VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011376
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011377 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011378 }
11379
John Wiegley429bb272011-04-08 18:41:53 +000011380 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall41d89032010-01-28 01:54:34 +000011381
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011382 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11383 // that calls this method, using Object for the implicit object
11384 // parameter and passing along the remaining arguments.
11385 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Webere0ff6902012-11-09 06:06:14 +000011386
11387 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber1a52a4d2012-11-09 08:38:04 +000011388 if (Method->isInvalidDecl())
Nico Webere0ff6902012-11-09 06:06:14 +000011389 return ExprError();
11390
Chandler Carruth6df868e2010-12-12 08:17:55 +000011391 const FunctionProtoType *Proto =
11392 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011393
11394 unsigned NumArgsInProto = Proto->getNumArgs();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011395 unsigned NumArgsToCheck = Args.size();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011396
11397 // Build the full argument list for the method call (the
11398 // implicit object parameter is placed at the beginning of the
11399 // list).
11400 Expr **MethodArgs;
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011401 if (Args.size() < NumArgsInProto) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011402 NumArgsToCheck = NumArgsInProto;
11403 MethodArgs = new Expr*[NumArgsInProto + 1];
11404 } else {
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011405 MethodArgs = new Expr*[Args.size() + 1];
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011406 }
John Wiegley429bb272011-04-08 18:41:53 +000011407 MethodArgs[0] = Object.get();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011408 for (unsigned ArgIdx = 0, e = Args.size(); ArgIdx != e; ++ArgIdx)
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011409 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +000011410
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011411 DeclarationNameInfo OpLocInfo(
11412 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11413 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011414 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011415 HadMultipleCandidates,
11416 OpLocInfo.getLoc(),
11417 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000011418 if (NewFn.isInvalid())
11419 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011420
11421 // Once we've built TheCall, all of the expressions are properly
11422 // owned.
John McCallf89e55a2010-11-18 06:31:45 +000011423 QualType ResultTy = Method->getResultType();
11424 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11425 ResultTy = ResultTy.getNonLValueExprType(Context);
11426
John McCall9ae2f072010-08-23 23:25:46 +000011427 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011428 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011429 llvm::makeArrayRef(MethodArgs, Args.size()+1),
Lang Hamesbe9af122012-10-02 04:45:10 +000011430 ResultTy, VK, RParenLoc, false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011431 delete [] MethodArgs;
11432
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011433 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +000011434 Method))
11435 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011436
Douglas Gregor518fda12009-01-13 05:10:00 +000011437 // We may have default arguments. If so, we need to allocate more
11438 // slots in the call for them.
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011439 if (Args.size() < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +000011440 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011441 else if (Args.size() > NumArgsInProto)
Douglas Gregor518fda12009-01-13 05:10:00 +000011442 NumArgsToCheck = NumArgsInProto;
11443
Chris Lattner312531a2009-04-12 08:11:20 +000011444 bool IsError = false;
11445
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011446 // Initialize the implicit object parameter.
John Wiegley429bb272011-04-08 18:41:53 +000011447 ExprResult ObjRes =
11448 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11449 Best->FoundDecl, Method);
11450 if (ObjRes.isInvalid())
11451 IsError = true;
11452 else
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011453 Object = ObjRes;
John Wiegley429bb272011-04-08 18:41:53 +000011454 TheCall->setArg(0, Object.take());
Chris Lattner312531a2009-04-12 08:11:20 +000011455
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011456 // Check the argument types.
11457 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011458 Expr *Arg;
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011459 if (i < Args.size()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011460 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +000011461
Douglas Gregor518fda12009-01-13 05:10:00 +000011462 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +000011463
John McCall60d7b3a2010-08-24 06:29:42 +000011464 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +000011465 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000011466 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +000011467 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +000011468 SourceLocation(), Arg);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011469
Anders Carlsson3faa4862010-01-29 18:43:53 +000011470 IsError |= InputInit.isInvalid();
11471 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011472 } else {
John McCall60d7b3a2010-08-24 06:29:42 +000011473 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +000011474 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11475 if (DefArg.isInvalid()) {
11476 IsError = true;
11477 break;
11478 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011479
Douglas Gregord47c47d2009-11-09 19:27:57 +000011480 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011481 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011482
11483 TheCall->setArg(i + 1, Arg);
11484 }
11485
11486 // If this is a variadic call, handle args passed through "...".
11487 if (Proto->isVariadic()) {
11488 // Promote the arguments (C99 6.5.2.2p7).
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011489 for (unsigned i = NumArgsInProto, e = Args.size(); i < e; i++) {
John Wiegley429bb272011-04-08 18:41:53 +000011490 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11491 IsError |= Arg.isInvalid();
11492 TheCall->setArg(i + 1, Arg.take());
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011493 }
11494 }
11495
Chris Lattner312531a2009-04-12 08:11:20 +000011496 if (IsError) return true;
11497
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011498 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmane61eb042012-02-18 04:48:30 +000011499
Richard Smith831421f2012-06-25 20:30:08 +000011500 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +000011501 return true;
11502
John McCall182f7092010-08-24 06:09:16 +000011503 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011504}
11505
Douglas Gregor8ba10742008-11-20 16:27:02 +000011506/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +000011507/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +000011508/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +000011509ExprResult
Kaelyn Uhrainbaaeb852013-07-31 17:38:24 +000011510Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
11511 bool *NoArrowOperatorFound) {
Chandler Carruth6df868e2010-12-12 08:17:55 +000011512 assert(Base->getType()->isRecordType() &&
11513 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +000011514
John McCall5acb0c92011-10-17 18:40:02 +000011515 if (checkPlaceholderForOverload(*this, Base))
11516 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000011517
John McCall5769d612010-02-08 23:07:23 +000011518 SourceLocation Loc = Base->getExprLoc();
11519
Douglas Gregor8ba10742008-11-20 16:27:02 +000011520 // C++ [over.ref]p1:
11521 //
11522 // [...] An expression x->m is interpreted as (x.operator->())->m
11523 // for a class object x of type T if T::operator->() exists and if
11524 // the operator is selected as the best match function by the
11525 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +000011526 DeclarationName OpName =
11527 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +000011528 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +000011529 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011530
John McCall5769d612010-02-08 23:07:23 +000011531 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000011532 diag::err_typecheck_incomplete_tag, Base))
Eli Friedmanf43fb722009-11-18 01:28:03 +000011533 return ExprError();
11534
John McCalla24dc2e2009-11-17 02:14:36 +000011535 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11536 LookupQualifiedName(R, BaseRecord->getDecl());
11537 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +000011538
11539 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +000011540 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011541 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko55431692013-05-05 00:41:58 +000011542 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +000011543 }
Douglas Gregor8ba10742008-11-20 16:27:02 +000011544
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011545 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11546
Douglas Gregor8ba10742008-11-20 16:27:02 +000011547 // Perform overload resolution.
11548 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000011549 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +000011550 case OR_Success:
11551 // Overload resolution succeeded; we'll build the call below.
11552 break;
11553
11554 case OR_No_Viable_Function:
Kaelyn Uhrain45c3ba72013-07-11 22:38:30 +000011555 if (CandidateSet.empty()) {
11556 QualType BaseType = Base->getType();
Kaelyn Uhrainbaaeb852013-07-31 17:38:24 +000011557 if (NoArrowOperatorFound) {
11558 // Report this specific error to the caller instead of emitting a
11559 // diagnostic, as requested.
11560 *NoArrowOperatorFound = true;
11561 return ExprError();
11562 }
Kaelyn Uhraind4224342013-07-15 19:54:54 +000011563 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
11564 << BaseType << Base->getSourceRange();
Kaelyn Uhrain45c3ba72013-07-11 22:38:30 +000011565 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhraind4224342013-07-15 19:54:54 +000011566 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain45c3ba72013-07-11 22:38:30 +000011567 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain45c3ba72013-07-11 22:38:30 +000011568 }
11569 } else
Douglas Gregor8ba10742008-11-20 16:27:02 +000011570 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011571 << "operator->" << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011572 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011573 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011574
11575 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000011576 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11577 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011578 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011579 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011580
11581 case OR_Deleted:
11582 Diag(OpLoc, diag::err_ovl_deleted_oper)
11583 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011584 << "->"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011585 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011586 << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011587 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011588 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011589 }
11590
John McCall9aa472c2010-03-19 07:35:19 +000011591 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
11592
Douglas Gregor8ba10742008-11-20 16:27:02 +000011593 // Convert the object parameter.
11594 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000011595 ExprResult BaseResult =
11596 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11597 Best->FoundDecl, Method);
11598 if (BaseResult.isInvalid())
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011599 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011600 Base = BaseResult.take();
Douglas Gregorfc195ef2008-11-21 03:04:22 +000011601
Douglas Gregor8ba10742008-11-20 16:27:02 +000011602 // Build the operator call.
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011603 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011604 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000011605 if (FnExpr.isInvalid())
11606 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011607
John McCallf89e55a2010-11-18 06:31:45 +000011608 QualType ResultTy = Method->getResultType();
11609 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11610 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +000011611 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011612 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000011613 Base, ResultTy, VK, OpLoc, false);
Anders Carlsson15ea3782009-10-13 22:43:21 +000011614
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011615 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000011616 Method))
11617 return ExprError();
Eli Friedmand5931902011-04-04 01:18:25 +000011618
11619 return MaybeBindToTemporary(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +000011620}
11621
Richard Smith36f5cfe2012-03-09 08:00:36 +000011622/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11623/// a literal operator described by the provided lookup results.
11624ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11625 DeclarationNameInfo &SuffixInfo,
11626 ArrayRef<Expr*> Args,
11627 SourceLocation LitEndLoc,
11628 TemplateArgumentListInfo *TemplateArgs) {
11629 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smith9fcce652012-03-07 08:35:16 +000011630
Richard Smith36f5cfe2012-03-09 08:00:36 +000011631 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11632 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11633 TemplateArgs);
Richard Smith9fcce652012-03-07 08:35:16 +000011634
Richard Smith36f5cfe2012-03-09 08:00:36 +000011635 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11636
Richard Smith36f5cfe2012-03-09 08:00:36 +000011637 // Perform overload resolution. This will usually be trivial, but might need
11638 // to perform substitutions for a literal operator template.
11639 OverloadCandidateSet::iterator Best;
11640 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11641 case OR_Success:
11642 case OR_Deleted:
11643 break;
11644
11645 case OR_No_Viable_Function:
11646 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11647 << R.getLookupName();
11648 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11649 return ExprError();
11650
11651 case OR_Ambiguous:
11652 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11653 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11654 return ExprError();
Richard Smith9fcce652012-03-07 08:35:16 +000011655 }
11656
Richard Smith36f5cfe2012-03-09 08:00:36 +000011657 FunctionDecl *FD = Best->Function;
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011658 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
11659 HadMultipleCandidates,
Richard Smith36f5cfe2012-03-09 08:00:36 +000011660 SuffixInfo.getLoc(),
11661 SuffixInfo.getInfo());
11662 if (Fn.isInvalid())
11663 return true;
Richard Smith9fcce652012-03-07 08:35:16 +000011664
11665 // Check the argument types. This should almost always be a no-op, except
11666 // that array-to-pointer decay is applied to string literals.
Richard Smith9fcce652012-03-07 08:35:16 +000011667 Expr *ConvArgs[2];
Richard Smith958ba642013-05-05 15:51:06 +000011668 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smith9fcce652012-03-07 08:35:16 +000011669 ExprResult InputInit = PerformCopyInitialization(
11670 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11671 SourceLocation(), Args[ArgIdx]);
11672 if (InputInit.isInvalid())
11673 return true;
11674 ConvArgs[ArgIdx] = InputInit.take();
11675 }
11676
Richard Smith9fcce652012-03-07 08:35:16 +000011677 QualType ResultTy = FD->getResultType();
11678 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11679 ResultTy = ResultTy.getNonLValueExprType(Context);
11680
Richard Smith9fcce652012-03-07 08:35:16 +000011681 UserDefinedLiteral *UDL =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000011682 new (Context) UserDefinedLiteral(Context, Fn.take(),
11683 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smith9fcce652012-03-07 08:35:16 +000011684 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11685
11686 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11687 return ExprError();
11688
Richard Smith831421f2012-06-25 20:30:08 +000011689 if (CheckFunctionCall(FD, UDL, NULL))
Richard Smith9fcce652012-03-07 08:35:16 +000011690 return ExprError();
11691
11692 return MaybeBindToTemporary(UDL);
11693}
11694
Sam Panzere1715b62012-08-21 00:52:01 +000011695/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11696/// given LookupResult is non-empty, it is assumed to describe a member which
11697/// will be invoked. Otherwise, the function will be found via argument
11698/// dependent lookup.
11699/// CallExpr is set to a valid expression and FRS_Success returned on success,
11700/// otherwise CallExpr is set to ExprError() and some non-success value
11701/// is returned.
11702Sema::ForRangeStatus
11703Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11704 SourceLocation RangeLoc, VarDecl *Decl,
11705 BeginEndFunction BEF,
11706 const DeclarationNameInfo &NameInfo,
11707 LookupResult &MemberLookup,
11708 OverloadCandidateSet *CandidateSet,
11709 Expr *Range, ExprResult *CallExpr) {
11710 CandidateSet->clear();
11711 if (!MemberLookup.empty()) {
11712 ExprResult MemberRef =
11713 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11714 /*IsPtr=*/false, CXXScopeSpec(),
11715 /*TemplateKWLoc=*/SourceLocation(),
11716 /*FirstQualifierInScope=*/0,
11717 MemberLookup,
11718 /*TemplateArgs=*/0);
11719 if (MemberRef.isInvalid()) {
11720 *CallExpr = ExprError();
11721 Diag(Range->getLocStart(), diag::note_in_for_range)
11722 << RangeLoc << BEF << Range->getType();
11723 return FRS_DiagnosticIssued;
11724 }
Dmitri Gribenko62ed8892013-05-05 20:40:26 +000011725 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, 0);
Sam Panzere1715b62012-08-21 00:52:01 +000011726 if (CallExpr->isInvalid()) {
11727 *CallExpr = ExprError();
11728 Diag(Range->getLocStart(), diag::note_in_for_range)
11729 << RangeLoc << BEF << Range->getType();
11730 return FRS_DiagnosticIssued;
11731 }
11732 } else {
11733 UnresolvedSet<0> FoundNames;
Sam Panzere1715b62012-08-21 00:52:01 +000011734 UnresolvedLookupExpr *Fn =
11735 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11736 NestedNameSpecifierLoc(), NameInfo,
11737 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb1502bc2012-10-18 17:56:02 +000011738 FoundNames.begin(), FoundNames.end());
Sam Panzere1715b62012-08-21 00:52:01 +000011739
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011740 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzere1715b62012-08-21 00:52:01 +000011741 CandidateSet, CallExpr);
11742 if (CandidateSet->empty() || CandidateSetError) {
11743 *CallExpr = ExprError();
11744 return FRS_NoViableFunction;
11745 }
11746 OverloadCandidateSet::iterator Best;
11747 OverloadingResult OverloadResult =
11748 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
11749
11750 if (OverloadResult == OR_No_Viable_Function) {
11751 *CallExpr = ExprError();
11752 return FRS_NoViableFunction;
11753 }
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011754 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Sam Panzere1715b62012-08-21 00:52:01 +000011755 Loc, 0, CandidateSet, &Best,
11756 OverloadResult,
11757 /*AllowTypoCorrection=*/false);
11758 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
11759 *CallExpr = ExprError();
11760 Diag(Range->getLocStart(), diag::note_in_for_range)
11761 << RangeLoc << BEF << Range->getType();
11762 return FRS_DiagnosticIssued;
11763 }
11764 }
11765 return FRS_Success;
11766}
11767
11768
Douglas Gregor904eed32008-11-10 20:40:00 +000011769/// FixOverloadedFunctionReference - E is an expression that refers to
11770/// a C++ overloaded function (possibly with some parentheses and
11771/// perhaps a '&' around it). We have resolved the overloaded function
11772/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +000011773/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +000011774Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +000011775 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +000011776 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011777 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11778 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011779 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011780 return PE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011781
Douglas Gregor699ee522009-11-20 19:42:02 +000011782 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011783 }
11784
Douglas Gregor699ee522009-11-20 19:42:02 +000011785 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011786 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11787 Found, Fn);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011788 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +000011789 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +000011790 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +000011791 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +000011792 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011793 return ICE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011794
11795 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallf871d0c2010-08-07 06:22:56 +000011796 ICE->getCastKind(),
11797 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +000011798 ICE->getValueKind());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011799 }
11800
Douglas Gregor699ee522009-11-20 19:42:02 +000011801 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +000011802 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +000011803 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +000011804 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11805 if (Method->isStatic()) {
11806 // Do nothing: static member functions aren't any different
11807 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +000011808 } else {
John McCallf7a1a742009-11-24 19:00:30 +000011809 // Fix the sub expression, which really has to be an
11810 // UnresolvedLookupExpr holding an overloaded member function
11811 // or template.
John McCall6bb80172010-03-30 21:47:33 +000011812 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11813 Found, Fn);
John McCallba135432009-11-21 08:51:07 +000011814 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011815 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +000011816
John McCallba135432009-11-21 08:51:07 +000011817 assert(isa<DeclRefExpr>(SubExpr)
11818 && "fixed to something other than a decl ref");
11819 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11820 && "fixed to a member ref with no nested name qualifier");
11821
11822 // We have taken the address of a pointer to member
11823 // function. Perform the computation here so that we get the
11824 // appropriate pointer to member type.
11825 QualType ClassType
11826 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11827 QualType MemPtrType
11828 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11829
John McCallf89e55a2010-11-18 06:31:45 +000011830 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11831 VK_RValue, OK_Ordinary,
11832 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +000011833 }
11834 }
John McCall6bb80172010-03-30 21:47:33 +000011835 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11836 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011837 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011838 return UnOp;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011839
John McCall2de56d12010-08-25 11:45:40 +000011840 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +000011841 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +000011842 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +000011843 UnOp->getOperatorLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011844 }
John McCallba135432009-11-21 08:51:07 +000011845
11846 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +000011847 // FIXME: avoid copy.
11848 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +000011849 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +000011850 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11851 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +000011852 }
11853
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011854 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11855 ULE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011856 ULE->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011857 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011858 /*enclosing*/ false, // FIXME?
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011859 ULE->getNameLoc(),
11860 Fn->getType(),
11861 VK_LValue,
11862 Found.getDecl(),
11863 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011864 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011865 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11866 return DRE;
John McCallba135432009-11-21 08:51:07 +000011867 }
11868
John McCall129e2df2009-11-30 22:42:35 +000011869 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +000011870 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +000011871 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11872 if (MemExpr->hasExplicitTemplateArgs()) {
11873 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11874 TemplateArgs = &TemplateArgsBuffer;
11875 }
John McCalld5532b62009-11-23 01:53:49 +000011876
John McCallaa81e162009-12-01 22:10:20 +000011877 Expr *Base;
11878
John McCallf89e55a2010-11-18 06:31:45 +000011879 // If we're filling in a static method where we used to have an
11880 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +000011881 if (MemExpr->isImplicitAccess()) {
11882 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011883 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11884 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011885 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011886 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011887 /*enclosing*/ false,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011888 MemExpr->getMemberLoc(),
11889 Fn->getType(),
11890 VK_LValue,
11891 Found.getDecl(),
11892 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011893 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011894 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11895 return DRE;
Douglas Gregor828a1972010-01-07 23:12:05 +000011896 } else {
11897 SourceLocation Loc = MemExpr->getMemberLoc();
11898 if (MemExpr->getQualifier())
Douglas Gregor4c9be892011-02-28 20:01:57 +000011899 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman72899c32012-01-07 04:59:52 +000011900 CheckCXXThisCapture(Loc);
Douglas Gregor828a1972010-01-07 23:12:05 +000011901 Base = new (Context) CXXThisExpr(Loc,
11902 MemExpr->getBaseType(),
11903 /*isImplicit=*/true);
11904 }
John McCallaa81e162009-12-01 22:10:20 +000011905 } else
John McCall3fa5cae2010-10-26 07:05:15 +000011906 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +000011907
John McCallf5307512011-04-27 00:36:17 +000011908 ExprValueKind valueKind;
11909 QualType type;
11910 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11911 valueKind = VK_LValue;
11912 type = Fn->getType();
11913 } else {
11914 valueKind = VK_RValue;
11915 type = Context.BoundMemberTy;
11916 }
11917
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011918 MemberExpr *ME = MemberExpr::Create(Context, Base,
11919 MemExpr->isArrow(),
11920 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011921 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011922 Fn,
11923 Found,
11924 MemExpr->getMemberNameInfo(),
11925 TemplateArgs,
11926 type, valueKind, OK_Ordinary);
11927 ME->setHadMultipleCandidates(true);
Richard Smith4a030222012-11-14 07:06:31 +000011928 MarkMemberReferenced(ME);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011929 return ME;
Douglas Gregor699ee522009-11-20 19:42:02 +000011930 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011931
John McCall3fa5cae2010-10-26 07:05:15 +000011932 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregor904eed32008-11-10 20:40:00 +000011933}
11934
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011935ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCall60d7b3a2010-08-24 06:29:42 +000011936 DeclAccessPair Found,
11937 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +000011938 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +000011939}
11940
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000011941} // end namespace clang