blob: 2c2cfd03b17ead2b24906ae2334eb48512a30c60 [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,
Douglas Gregor1ce55092013-11-07 22:34:54 +000085 bool AllowExplicit,
86 bool AllowObjCConversionOnExplicit);
John McCall120d63c2010-08-24 20:38:10 +000087
88
89static ImplicitConversionSequence::CompareKind
90CompareStandardConversionSequences(Sema &S,
91 const StandardConversionSequence& SCS1,
92 const StandardConversionSequence& SCS2);
93
94static ImplicitConversionSequence::CompareKind
95CompareQualificationConversions(Sema &S,
96 const StandardConversionSequence& SCS1,
97 const StandardConversionSequence& SCS2);
98
99static ImplicitConversionSequence::CompareKind
100CompareDerivedToBaseConversions(Sema &S,
101 const StandardConversionSequence& SCS1,
102 const StandardConversionSequence& SCS2);
103
104
105
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000106/// GetConversionCategory - Retrieve the implicit conversion
107/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +0000108ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000109GetConversionCategory(ImplicitConversionKind Kind) {
110 static const ImplicitConversionCategory
111 Category[(int)ICK_Num_Conversion_Kinds] = {
112 ICC_Identity,
113 ICC_Lvalue_Transformation,
114 ICC_Lvalue_Transformation,
115 ICC_Lvalue_Transformation,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000116 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000117 ICC_Qualification_Adjustment,
118 ICC_Promotion,
119 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000120 ICC_Promotion,
121 ICC_Conversion,
122 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000123 ICC_Conversion,
124 ICC_Conversion,
125 ICC_Conversion,
126 ICC_Conversion,
127 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000128 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000129 ICC_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000130 ICC_Conversion,
131 ICC_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000132 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000133 ICC_Conversion
134 };
135 return Category[(int)Kind];
136}
137
138/// GetConversionRank - Retrieve the implicit conversion rank
139/// corresponding to the given implicit conversion kind.
140ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
141 static const ImplicitConversionRank
142 Rank[(int)ICK_Num_Conversion_Kinds] = {
143 ICR_Exact_Match,
144 ICR_Exact_Match,
145 ICR_Exact_Match,
146 ICR_Exact_Match,
147 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000148 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000149 ICR_Promotion,
150 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000151 ICR_Promotion,
152 ICR_Conversion,
153 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000154 ICR_Conversion,
155 ICR_Conversion,
156 ICR_Conversion,
157 ICR_Conversion,
158 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000159 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000160 ICR_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000161 ICR_Conversion,
162 ICR_Conversion,
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000163 ICR_Complex_Real_Conversion,
164 ICR_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000165 ICR_Conversion,
166 ICR_Writeback_Conversion
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000167 };
168 return Rank[(int)Kind];
169}
170
171/// GetImplicitConversionName - Return the name of this kind of
172/// implicit conversion.
173const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +0000174 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000175 "No conversion",
176 "Lvalue-to-rvalue",
177 "Array-to-pointer",
178 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +0000179 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000180 "Qualification",
181 "Integral promotion",
182 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000183 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000184 "Integral conversion",
185 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000186 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000187 "Floating-integral conversion",
188 "Pointer conversion",
189 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000190 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000191 "Compatible-types conversion",
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000192 "Derived-to-base conversion",
193 "Vector conversion",
194 "Vector splat",
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000195 "Complex-real conversion",
196 "Block Pointer conversion",
197 "Transparent Union Conversion"
John McCallf85e1932011-06-15 23:02:42 +0000198 "Writeback conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000199 };
200 return Name[Kind];
201}
202
Douglas Gregor60d62c22008-10-31 16:23:19 +0000203/// StandardConversionSequence - Set the standard conversion
204/// sequence to the identity conversion.
205void StandardConversionSequence::setAsIdentityConversion() {
206 First = ICK_Identity;
207 Second = ICK_Identity;
208 Third = ICK_Identity;
Douglas Gregora9bff302010-02-28 18:30:25 +0000209 DeprecatedStringLiteralToCharPtr = false;
John McCallf85e1932011-06-15 23:02:42 +0000210 QualificationIncludesObjCLifetime = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000211 ReferenceBinding = false;
212 DirectBinding = false;
Douglas Gregor440a4832011-01-26 14:52:12 +0000213 IsLvalueReference = true;
214 BindsToFunctionLvalue = false;
215 BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +0000216 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +0000217 ObjCLifetimeConversionBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000218 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000219}
220
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000221/// getRank - Retrieve the rank of this standard conversion sequence
222/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
223/// implicit conversions.
224ImplicitConversionRank StandardConversionSequence::getRank() const {
225 ImplicitConversionRank Rank = ICR_Exact_Match;
226 if (GetConversionRank(First) > Rank)
227 Rank = GetConversionRank(First);
228 if (GetConversionRank(Second) > Rank)
229 Rank = GetConversionRank(Second);
230 if (GetConversionRank(Third) > Rank)
231 Rank = GetConversionRank(Third);
232 return Rank;
233}
234
235/// isPointerConversionToBool - Determines whether this conversion is
236/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000237/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000238/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000239bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000240 // Note that FromType has not necessarily been transformed by the
241 // array-to-pointer or function-to-pointer implicit conversions, so
242 // check for their presence as well as checking whether FromType is
243 // a pointer.
Douglas Gregorad323a82010-01-27 03:51:04 +0000244 if (getToType(1)->isBooleanType() &&
John McCallddb0ce72010-06-11 10:04:22 +0000245 (getFromType()->isPointerType() ||
246 getFromType()->isObjCObjectPointerType() ||
247 getFromType()->isBlockPointerType() ||
Anders Carlssonc8df0b62010-11-05 00:12:09 +0000248 getFromType()->isNullPtrType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000249 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
250 return true;
251
252 return false;
253}
254
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000255/// isPointerConversionToVoidPointer - Determines whether this
256/// conversion is a conversion of a pointer to a void pointer. This is
257/// used as part of the ranking of standard conversion sequences (C++
258/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000259bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000260StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000261isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000262 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000263 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000264
265 // Note that FromType has not necessarily been transformed by the
266 // array-to-pointer implicit conversion, so check for its presence
267 // and redo the conversion to get a pointer.
268 if (First == ICK_Array_To_Pointer)
269 FromType = Context.getArrayDecayedType(FromType);
270
Douglas Gregorf9af5242011-04-15 20:45:44 +0000271 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000272 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000273 return ToPtrType->getPointeeType()->isVoidType();
274
275 return false;
276}
277
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000278/// Skip any implicit casts which could be either part of a narrowing conversion
279/// or after one in an implicit conversion.
280static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
281 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
282 switch (ICE->getCastKind()) {
283 case CK_NoOp:
284 case CK_IntegralCast:
285 case CK_IntegralToBoolean:
286 case CK_IntegralToFloating:
287 case CK_FloatingToIntegral:
288 case CK_FloatingToBoolean:
289 case CK_FloatingCast:
290 Converted = ICE->getSubExpr();
291 continue;
292
293 default:
294 return Converted;
295 }
296 }
297
298 return Converted;
299}
300
301/// Check if this standard conversion sequence represents a narrowing
302/// conversion, according to C++11 [dcl.init.list]p7.
303///
304/// \param Ctx The AST context.
305/// \param Converted The result of applying this standard conversion sequence.
306/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
307/// value of the expression prior to the narrowing conversion.
Richard Smithf6028062012-03-23 23:55:39 +0000308/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
309/// type of the expression prior to the narrowing conversion.
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000310NarrowingKind
Richard Smith8ef7b202012-01-18 23:55:52 +0000311StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
312 const Expr *Converted,
Richard Smithf6028062012-03-23 23:55:39 +0000313 APValue &ConstantValue,
314 QualType &ConstantType) const {
David Blaikie4e4d0842012-03-11 07:00:24 +0000315 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000316
317 // C++11 [dcl.init.list]p7:
318 // A narrowing conversion is an implicit conversion ...
319 QualType FromType = getToType(0);
320 QualType ToType = getToType(1);
321 switch (Second) {
322 // -- from a floating-point type to an integer type, or
323 //
324 // -- from an integer type or unscoped enumeration type to a floating-point
325 // type, except where the source is a constant expression and the actual
326 // value after conversion will fit into the target type and will produce
327 // the original value when converted back to the original type, or
328 case ICK_Floating_Integral:
329 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
330 return NK_Type_Narrowing;
331 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
332 llvm::APSInt IntConstantValue;
333 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
334 if (Initializer &&
335 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
336 // Convert the integer to the floating type.
337 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
338 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
339 llvm::APFloat::rmNearestTiesToEven);
340 // And back.
341 llvm::APSInt ConvertedValue = IntConstantValue;
342 bool ignored;
343 Result.convertToInteger(ConvertedValue,
344 llvm::APFloat::rmTowardZero, &ignored);
345 // If the resulting value is different, this was a narrowing conversion.
346 if (IntConstantValue != ConvertedValue) {
347 ConstantValue = APValue(IntConstantValue);
Richard Smithf6028062012-03-23 23:55:39 +0000348 ConstantType = Initializer->getType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000349 return NK_Constant_Narrowing;
350 }
351 } else {
352 // Variables are always narrowings.
353 return NK_Variable_Narrowing;
354 }
355 }
356 return NK_Not_Narrowing;
357
358 // -- from long double to double or float, or from double to float, except
359 // where the source is a constant expression and the actual value after
360 // conversion is within the range of values that can be represented (even
361 // if it cannot be represented exactly), or
362 case ICK_Floating_Conversion:
363 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
364 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
365 // FromType is larger than ToType.
366 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
367 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
368 // Constant!
369 assert(ConstantValue.isFloat());
370 llvm::APFloat FloatVal = ConstantValue.getFloat();
371 // Convert the source value into the target type.
372 bool ignored;
373 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
374 Ctx.getFloatTypeSemantics(ToType),
375 llvm::APFloat::rmNearestTiesToEven, &ignored);
376 // If there was no overflow, the source value is within the range of
377 // values that can be represented.
Richard Smithf6028062012-03-23 23:55:39 +0000378 if (ConvertStatus & llvm::APFloat::opOverflow) {
379 ConstantType = Initializer->getType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000380 return NK_Constant_Narrowing;
Richard Smithf6028062012-03-23 23:55:39 +0000381 }
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000382 } else {
383 return NK_Variable_Narrowing;
384 }
385 }
386 return NK_Not_Narrowing;
387
388 // -- from an integer type or unscoped enumeration type to an integer type
389 // that cannot represent all the values of the original type, except where
390 // the source is a constant expression and the actual value after
391 // conversion will fit into the target type and will produce the original
392 // value when converted back to the original type.
393 case ICK_Boolean_Conversion: // Bools are integers too.
394 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
395 // Boolean conversions can be from pointers and pointers to members
396 // [conv.bool], and those aren't considered narrowing conversions.
397 return NK_Not_Narrowing;
398 } // Otherwise, fall through to the integral case.
399 case ICK_Integral_Conversion: {
400 assert(FromType->isIntegralOrUnscopedEnumerationType());
401 assert(ToType->isIntegralOrUnscopedEnumerationType());
402 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
403 const unsigned FromWidth = Ctx.getIntWidth(FromType);
404 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
405 const unsigned ToWidth = Ctx.getIntWidth(ToType);
406
407 if (FromWidth > ToWidth ||
Richard Smithcd65f492012-06-13 01:07:41 +0000408 (FromWidth == ToWidth && FromSigned != ToSigned) ||
409 (FromSigned && !ToSigned)) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000410 // Not all values of FromType can be represented in ToType.
411 llvm::APSInt InitializerValue;
412 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smithcd65f492012-06-13 01:07:41 +0000413 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
414 // Such conversions on variables are always narrowing.
415 return NK_Variable_Narrowing;
Richard Smith5d7700e2012-06-19 21:28:35 +0000416 }
417 bool Narrowing = false;
418 if (FromWidth < ToWidth) {
Richard Smithcd65f492012-06-13 01:07:41 +0000419 // Negative -> unsigned is narrowing. Otherwise, more bits is never
420 // narrowing.
421 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith5d7700e2012-06-19 21:28:35 +0000422 Narrowing = true;
Richard Smithcd65f492012-06-13 01:07:41 +0000423 } else {
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000424 // Add a bit to the InitializerValue so we don't have to worry about
425 // signed vs. unsigned comparisons.
426 InitializerValue = InitializerValue.extend(
427 InitializerValue.getBitWidth() + 1);
428 // Convert the initializer to and from the target width and signed-ness.
429 llvm::APSInt ConvertedValue = InitializerValue;
430 ConvertedValue = ConvertedValue.trunc(ToWidth);
431 ConvertedValue.setIsSigned(ToSigned);
432 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
433 ConvertedValue.setIsSigned(InitializerValue.isSigned());
434 // If the result is different, this was a narrowing conversion.
Richard Smith5d7700e2012-06-19 21:28:35 +0000435 if (ConvertedValue != InitializerValue)
436 Narrowing = true;
437 }
438 if (Narrowing) {
439 ConstantType = Initializer->getType();
440 ConstantValue = APValue(InitializerValue);
441 return NK_Constant_Narrowing;
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000442 }
443 }
444 return NK_Not_Narrowing;
445 }
446
447 default:
448 // Other kinds of conversions are not narrowings.
449 return NK_Not_Narrowing;
450 }
451}
452
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000453/// DebugPrint - Print this standard conversion sequence to standard
454/// error. Useful for debugging overloading issues.
455void StandardConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000456 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000457 bool PrintedSomething = false;
458 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000459 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000460 PrintedSomething = true;
461 }
462
463 if (Second != ICK_Identity) {
464 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000465 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000466 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000467 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000468
469 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000470 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000471 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000472 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000473 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000474 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000475 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000476 PrintedSomething = true;
477 }
478
479 if (Third != ICK_Identity) {
480 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000481 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000482 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000483 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000484 PrintedSomething = true;
485 }
486
487 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000488 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000489 }
490}
491
492/// DebugPrint - Print this user-defined conversion sequence to standard
493/// error. Useful for debugging overloading issues.
494void UserDefinedConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000495 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000496 if (Before.First || Before.Second || Before.Third) {
497 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000498 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000499 }
Sebastian Redlcc7a6482011-11-01 15:53:09 +0000500 if (ConversionFunction)
501 OS << '\'' << *ConversionFunction << '\'';
502 else
503 OS << "aggregate initialization";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000504 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000505 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000506 After.DebugPrint();
507 }
508}
509
510/// DebugPrint - Print this implicit conversion sequence to standard
511/// error. Useful for debugging overloading issues.
512void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000513 raw_ostream &OS = llvm::errs();
Richard Smith798186a2013-09-06 22:30:28 +0000514 if (isStdInitializerListElement())
515 OS << "Worst std::initializer_list element conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000516 switch (ConversionKind) {
517 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000518 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000519 Standard.DebugPrint();
520 break;
521 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000522 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000523 UserDefined.DebugPrint();
524 break;
525 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000526 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000527 break;
John McCall1d318332010-01-12 00:44:57 +0000528 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000529 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000530 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000531 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000532 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000533 break;
534 }
535
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000536 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000537}
538
John McCall1d318332010-01-12 00:44:57 +0000539void AmbiguousConversionSequence::construct() {
540 new (&conversions()) ConversionSet();
541}
542
543void AmbiguousConversionSequence::destruct() {
544 conversions().~ConversionSet();
545}
546
547void
548AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
549 FromTypePtr = O.FromTypePtr;
550 ToTypePtr = O.ToTypePtr;
551 new (&conversions()) ConversionSet(O.conversions());
552}
553
Douglas Gregora9333192010-05-08 17:41:32 +0000554namespace {
Larisse Voufo43847122013-07-19 23:00:19 +0000555 // Structure used by DeductionFailureInfo to store
Richard Smith29805ca2013-01-31 05:19:49 +0000556 // template argument information.
557 struct DFIArguments {
Douglas Gregora9333192010-05-08 17:41:32 +0000558 TemplateArgument FirstArg;
559 TemplateArgument SecondArg;
560 };
Larisse Voufo43847122013-07-19 23:00:19 +0000561 // Structure used by DeductionFailureInfo to store
Richard Smith29805ca2013-01-31 05:19:49 +0000562 // template parameter and template argument information.
563 struct DFIParamWithArguments : DFIArguments {
564 TemplateParameter Param;
565 };
Douglas Gregora9333192010-05-08 17:41:32 +0000566}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000567
Douglas Gregora9333192010-05-08 17:41:32 +0000568/// \brief Convert from Sema's representation of template deduction information
569/// to the form used in overload-candidate information.
Larisse Voufo43847122013-07-19 23:00:19 +0000570DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context,
571 Sema::TemplateDeductionResult TDK,
572 TemplateDeductionInfo &Info) {
573 DeductionFailureInfo Result;
Douglas Gregora9333192010-05-08 17:41:32 +0000574 Result.Result = static_cast<unsigned>(TDK);
Richard Smithb8590f32012-05-07 09:03:25 +0000575 Result.HasDiagnostic = false;
Douglas Gregora9333192010-05-08 17:41:32 +0000576 Result.Data = 0;
577 switch (TDK) {
578 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000579 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000580 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000581 case Sema::TDK_TooManyArguments:
582 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000583 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000584
Douglas Gregora9333192010-05-08 17:41:32 +0000585 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000586 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000587 Result.Data = Info.Param.getOpaqueValue();
588 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000589
Richard Smith29805ca2013-01-31 05:19:49 +0000590 case Sema::TDK_NonDeducedMismatch: {
591 // FIXME: Should allocate from normal heap so that we can free this later.
592 DFIArguments *Saved = new (Context) DFIArguments;
593 Saved->FirstArg = Info.FirstArg;
594 Saved->SecondArg = Info.SecondArg;
595 Result.Data = Saved;
596 break;
597 }
598
Douglas Gregora9333192010-05-08 17:41:32 +0000599 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000600 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000601 // FIXME: Should allocate from normal heap so that we can free this later.
602 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000603 Saved->Param = Info.Param;
604 Saved->FirstArg = Info.FirstArg;
605 Saved->SecondArg = Info.SecondArg;
606 Result.Data = Saved;
607 break;
608 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000609
Douglas Gregora9333192010-05-08 17:41:32 +0000610 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000611 Result.Data = Info.take();
Richard Smithb8590f32012-05-07 09:03:25 +0000612 if (Info.hasSFINAEDiagnostic()) {
613 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
614 SourceLocation(), PartialDiagnostic::NullDiagnostic());
615 Info.takeSFINAEDiagnostic(*Diag);
616 Result.HasDiagnostic = true;
617 }
Douglas Gregorec20f462010-05-08 20:07:26 +0000618 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000619
Douglas Gregora9333192010-05-08 17:41:32 +0000620 case Sema::TDK_FailedOverloadResolution:
Richard Smith0efa62f2013-01-31 04:03:12 +0000621 Result.Data = Info.Expression;
622 break;
623
Richard Smith29805ca2013-01-31 05:19:49 +0000624 case Sema::TDK_MiscellaneousDeductionFailure:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000625 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000626 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000627
Douglas Gregora9333192010-05-08 17:41:32 +0000628 return Result;
629}
John McCall1d318332010-01-12 00:44:57 +0000630
Larisse Voufo43847122013-07-19 23:00:19 +0000631void DeductionFailureInfo::Destroy() {
Douglas Gregora9333192010-05-08 17:41:32 +0000632 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
633 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000634 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000635 case Sema::TDK_InstantiationDepth:
636 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000637 case Sema::TDK_TooManyArguments:
638 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000639 case Sema::TDK_InvalidExplicitArguments:
Richard Smith29805ca2013-01-31 05:19:49 +0000640 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000641 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000642
Douglas Gregora9333192010-05-08 17:41:32 +0000643 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000644 case Sema::TDK_Underqualified:
Richard Smith29805ca2013-01-31 05:19:49 +0000645 case Sema::TDK_NonDeducedMismatch:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000646 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000647 Data = 0;
648 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000649
650 case Sema::TDK_SubstitutionFailure:
Richard Smithb8590f32012-05-07 09:03:25 +0000651 // FIXME: Destroy the template argument list?
Douglas Gregorec20f462010-05-08 20:07:26 +0000652 Data = 0;
Richard Smithb8590f32012-05-07 09:03:25 +0000653 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
654 Diag->~PartialDiagnosticAt();
655 HasDiagnostic = false;
656 }
Douglas Gregorec20f462010-05-08 20:07:26 +0000657 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000658
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000659 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000660 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000661 break;
662 }
663}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000664
Larisse Voufo43847122013-07-19 23:00:19 +0000665PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smithb8590f32012-05-07 09:03:25 +0000666 if (HasDiagnostic)
667 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
668 return 0;
669}
670
Larisse Voufo43847122013-07-19 23:00:19 +0000671TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregora9333192010-05-08 17:41:32 +0000672 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
673 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000674 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000675 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000676 case Sema::TDK_TooManyArguments:
677 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000678 case Sema::TDK_SubstitutionFailure:
Richard Smith29805ca2013-01-31 05:19:49 +0000679 case Sema::TDK_NonDeducedMismatch:
680 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000681 return TemplateParameter();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000682
Douglas Gregora9333192010-05-08 17:41:32 +0000683 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000684 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000685 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregora9333192010-05-08 17:41:32 +0000686
687 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000688 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000689 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000690
Douglas Gregora9333192010-05-08 17:41:32 +0000691 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000692 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000693 break;
694 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000695
Douglas Gregora9333192010-05-08 17:41:32 +0000696 return TemplateParameter();
697}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000698
Larisse Voufo43847122013-07-19 23:00:19 +0000699TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregorec20f462010-05-08 20:07:26 +0000700 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith29805ca2013-01-31 05:19:49 +0000701 case Sema::TDK_Success:
702 case Sema::TDK_Invalid:
703 case Sema::TDK_InstantiationDepth:
704 case Sema::TDK_TooManyArguments:
705 case Sema::TDK_TooFewArguments:
706 case Sema::TDK_Incomplete:
707 case Sema::TDK_InvalidExplicitArguments:
708 case Sema::TDK_Inconsistent:
709 case Sema::TDK_Underqualified:
710 case Sema::TDK_NonDeducedMismatch:
711 case Sema::TDK_FailedOverloadResolution:
712 return 0;
Douglas Gregorec20f462010-05-08 20:07:26 +0000713
Richard Smith29805ca2013-01-31 05:19:49 +0000714 case Sema::TDK_SubstitutionFailure:
715 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000716
Richard Smith29805ca2013-01-31 05:19:49 +0000717 // Unhandled
718 case Sema::TDK_MiscellaneousDeductionFailure:
719 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000720 }
721
722 return 0;
723}
724
Larisse Voufo43847122013-07-19 23:00:19 +0000725const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregora9333192010-05-08 17:41:32 +0000726 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
727 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000728 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000729 case Sema::TDK_InstantiationDepth:
730 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000731 case Sema::TDK_TooManyArguments:
732 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000733 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000734 case Sema::TDK_SubstitutionFailure:
Richard Smith29805ca2013-01-31 05:19:49 +0000735 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000736 return 0;
737
Douglas Gregora9333192010-05-08 17:41:32 +0000738 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000739 case Sema::TDK_Underqualified:
Richard Smith29805ca2013-01-31 05:19:49 +0000740 case Sema::TDK_NonDeducedMismatch:
741 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000742
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000743 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000744 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000745 break;
746 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000747
Douglas Gregora9333192010-05-08 17:41:32 +0000748 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000749}
Douglas Gregora9333192010-05-08 17:41:32 +0000750
Larisse Voufo43847122013-07-19 23:00:19 +0000751const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregora9333192010-05-08 17:41:32 +0000752 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
753 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000754 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000755 case Sema::TDK_InstantiationDepth:
756 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000757 case Sema::TDK_TooManyArguments:
758 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000759 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000760 case Sema::TDK_SubstitutionFailure:
Richard Smith29805ca2013-01-31 05:19:49 +0000761 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000762 return 0;
763
Douglas Gregora9333192010-05-08 17:41:32 +0000764 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000765 case Sema::TDK_Underqualified:
Richard Smith29805ca2013-01-31 05:19:49 +0000766 case Sema::TDK_NonDeducedMismatch:
767 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000768
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000769 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000770 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000771 break;
772 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000773
Douglas Gregora9333192010-05-08 17:41:32 +0000774 return 0;
775}
776
Larisse Voufo43847122013-07-19 23:00:19 +0000777Expr *DeductionFailureInfo::getExpr() {
Richard Smith0efa62f2013-01-31 04:03:12 +0000778 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
779 Sema::TDK_FailedOverloadResolution)
780 return static_cast<Expr*>(Data);
781
782 return 0;
783}
784
Benjamin Kramerf5b132f2012-10-09 15:52:25 +0000785void OverloadCandidateSet::destroyCandidates() {
Richard Smithe3898ac2012-07-18 23:52:59 +0000786 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer9e2822b2012-01-14 20:16:52 +0000787 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
788 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smithe3898ac2012-07-18 23:52:59 +0000789 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
790 i->DeductionFailure.Destroy();
791 }
Benjamin Kramerf5b132f2012-10-09 15:52:25 +0000792}
793
794void OverloadCandidateSet::clear() {
795 destroyCandidates();
Benjamin Kramer314f5542012-01-14 19:31:39 +0000796 NumInlineSequences = 0;
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +0000797 Candidates.clear();
Douglas Gregora9333192010-05-08 17:41:32 +0000798 Functions.clear();
799}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000800
John McCall5acb0c92011-10-17 18:40:02 +0000801namespace {
802 class UnbridgedCastsSet {
803 struct Entry {
804 Expr **Addr;
805 Expr *Saved;
806 };
807 SmallVector<Entry, 2> Entries;
808
809 public:
810 void save(Sema &S, Expr *&E) {
811 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
812 Entry entry = { &E, E };
813 Entries.push_back(entry);
814 E = S.stripARCUnbridgedCast(E);
815 }
816
817 void restore() {
818 for (SmallVectorImpl<Entry>::iterator
819 i = Entries.begin(), e = Entries.end(); i != e; ++i)
820 *i->Addr = i->Saved;
821 }
822 };
823}
824
825/// checkPlaceholderForOverload - Do any interesting placeholder-like
826/// preprocessing on the given expression.
827///
828/// \param unbridgedCasts a collection to which to add unbridged casts;
829/// without this, they will be immediately diagnosed as errors
830///
831/// Return true on unrecoverable error.
832static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
833 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall5acb0c92011-10-17 18:40:02 +0000834 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
835 // We can't handle overloaded expressions here because overload
836 // resolution might reasonably tweak them.
837 if (placeholder->getKind() == BuiltinType::Overload) return false;
838
839 // If the context potentially accepts unbridged ARC casts, strip
840 // the unbridged cast and add it to the collection for later restoration.
841 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
842 unbridgedCasts) {
843 unbridgedCasts->save(S, E);
844 return false;
845 }
846
847 // Go ahead and check everything else.
848 ExprResult result = S.CheckPlaceholderExpr(E);
849 if (result.isInvalid())
850 return true;
851
852 E = result.take();
853 return false;
854 }
855
856 // Nothing to do.
857 return false;
858}
859
860/// checkArgPlaceholdersForOverload - Check a set of call operands for
861/// placeholders.
Dmitri Gribenko9e00f122013-05-09 21:02:07 +0000862static bool checkArgPlaceholdersForOverload(Sema &S,
863 MultiExprArg Args,
John McCall5acb0c92011-10-17 18:40:02 +0000864 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9e00f122013-05-09 21:02:07 +0000865 for (unsigned i = 0, e = Args.size(); i != e; ++i)
866 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall5acb0c92011-10-17 18:40:02 +0000867 return true;
868
869 return false;
870}
871
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000872// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000873// overload of the declarations in Old. This routine returns false if
874// New and Old cannot be overloaded, e.g., if New has the same
875// signature as some function in Old (C++ 1.3.10) or if the Old
876// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000877// it does return false, MatchedDecl will point to the decl that New
878// cannot be overloaded with. This decl may be a UsingShadowDecl on
879// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000880//
881// Example: Given the following input:
882//
883// void f(int, float); // #1
884// void f(int, int); // #2
885// int f(int, int); // #3
886//
887// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000888// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000889//
John McCall51fa86f2009-12-02 08:47:38 +0000890// When we process #2, Old contains only the FunctionDecl for #1. By
891// comparing the parameter types, we see that #1 and #2 are overloaded
892// (since they have different signatures), so this routine returns
893// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000894//
John McCall51fa86f2009-12-02 08:47:38 +0000895// When we process #3, Old is an overload set containing #1 and #2. We
896// compare the signatures of #3 to #1 (they're overloaded, so we do
897// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
898// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000899// signature), IsOverload returns false and MatchedDecl will be set to
900// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000901//
902// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
903// into a class by a using declaration. The rules for whether to hide
904// shadow declarations ignore some properties which otherwise figure
905// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000906Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000907Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
908 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000909 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000910 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000911 NamedDecl *OldD = *I;
912
913 bool OldIsUsingDecl = false;
914 if (isa<UsingShadowDecl>(OldD)) {
915 OldIsUsingDecl = true;
916
917 // We can always introduce two using declarations into the same
918 // context, even if they have identical signatures.
919 if (NewIsUsingDecl) continue;
920
921 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
922 }
923
924 // If either declaration was introduced by a using declaration,
925 // we'll need to use slightly different rules for matching.
926 // Essentially, these rules are the normal rules, except that
927 // function templates hide function templates with different
928 // return types or template parameter lists.
929 bool UseMemberUsingDeclRules =
John McCall78037ac2013-04-03 21:19:47 +0000930 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
931 !New->getFriendObjectKind();
John McCallad00b772010-06-16 08:42:20 +0000932
John McCall51fa86f2009-12-02 08:47:38 +0000933 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000934 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
935 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
936 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
937 continue;
938 }
939
John McCall871b2e72009-12-09 03:35:25 +0000940 Match = *I;
941 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000942 }
John McCall51fa86f2009-12-02 08:47:38 +0000943 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000944 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
945 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
946 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
947 continue;
948 }
949
Rafael Espindola90cc3902013-04-15 12:49:13 +0000950 if (!shouldLinkPossiblyHiddenDecl(*I, New))
951 continue;
952
John McCall871b2e72009-12-09 03:35:25 +0000953 Match = *I;
954 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000955 }
John McCalld7945c62010-11-10 03:01:53 +0000956 } else if (isa<UsingDecl>(OldD)) {
John McCall9f54ad42009-12-10 09:41:52 +0000957 // We can overload with these, which can show up when doing
958 // redeclaration checks for UsingDecls.
959 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalld7945c62010-11-10 03:01:53 +0000960 } else if (isa<TagDecl>(OldD)) {
961 // We can always overload with tags by hiding them.
John McCall9f54ad42009-12-10 09:41:52 +0000962 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
963 // Optimistically assume that an unresolved using decl will
964 // overload; if it doesn't, we'll have to diagnose during
965 // template instantiation.
966 } else {
John McCall68263142009-11-18 22:49:29 +0000967 // (C++ 13p1):
968 // Only function declarations can be overloaded; object and type
969 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000970 Match = *I;
971 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000972 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000973 }
John McCall68263142009-11-18 22:49:29 +0000974
John McCall871b2e72009-12-09 03:35:25 +0000975 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000976}
977
Richard Smithaa4bc182013-06-30 09:48:50 +0000978bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
979 bool UseUsingDeclRules) {
980 // C++ [basic.start.main]p2: This function shall not be overloaded.
981 if (New->isMain())
Rafael Espindola78eeba82012-12-28 14:21:58 +0000982 return false;
Rafael Espindola7a525ac2013-01-12 01:47:40 +0000983
David Majnemere9f6f332013-09-16 22:44:20 +0000984 // MSVCRT user defined entry points cannot be overloaded.
985 if (New->isMSVCRTEntryPoint())
986 return false;
987
John McCall68263142009-11-18 22:49:29 +0000988 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
989 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
990
991 // C++ [temp.fct]p2:
992 // A function template can be overloaded with other function templates
993 // and with normal (non-template) functions.
994 if ((OldTemplate == 0) != (NewTemplate == 0))
995 return true;
996
997 // Is the function New an overload of the function Old?
Richard Smithaa4bc182013-06-30 09:48:50 +0000998 QualType OldQType = Context.getCanonicalType(Old->getType());
999 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall68263142009-11-18 22:49:29 +00001000
1001 // Compare the signatures (C++ 1.3.10) of the two functions to
1002 // determine whether they are overloads. If we find any mismatch
1003 // in the signature, they are overloads.
1004
1005 // If either of these functions is a K&R-style function (no
1006 // prototype), then we consider them to have matching signatures.
1007 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1008 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1009 return false;
1010
John McCallf4c73712011-01-19 06:33:43 +00001011 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
1012 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall68263142009-11-18 22:49:29 +00001013
1014 // The signature of a function includes the types of its
1015 // parameters (C++ 1.3.10), which includes the presence or absence
1016 // of the ellipsis; see C++ DR 357).
1017 if (OldQType != NewQType &&
1018 (OldType->getNumArgs() != NewType->getNumArgs() ||
1019 OldType->isVariadic() != NewType->isVariadic() ||
Richard Smithaa4bc182013-06-30 09:48:50 +00001020 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +00001021 return true;
1022
1023 // C++ [temp.over.link]p4:
1024 // The signature of a function template consists of its function
1025 // signature, its return type and its template parameter list. The names
1026 // of the template parameters are significant only for establishing the
1027 // relationship between the template parameters and the rest of the
1028 // signature.
1029 //
1030 // We check the return type and template parameter lists for function
1031 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +00001032 //
1033 // However, we don't consider either of these when deciding whether
1034 // a member introduced by a shadow declaration is hidden.
1035 if (!UseUsingDeclRules && NewTemplate &&
Richard Smithaa4bc182013-06-30 09:48:50 +00001036 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1037 OldTemplate->getTemplateParameters(),
1038 false, TPL_TemplateMatch) ||
John McCall68263142009-11-18 22:49:29 +00001039 OldType->getResultType() != NewType->getResultType()))
1040 return true;
1041
1042 // If the function is a class member, its signature includes the
Douglas Gregor57c9f4f2011-01-26 17:47:49 +00001043 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall68263142009-11-18 22:49:29 +00001044 //
1045 // As part of this, also check whether one of the member functions
1046 // is static, in which case they are not overloads (C++
1047 // 13.1p2). While not part of the definition of the signature,
1048 // this check is important to determine whether these functions
1049 // can be overloaded.
Richard Smith21c8fa82013-01-14 05:37:29 +00001050 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1051 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall68263142009-11-18 22:49:29 +00001052 if (OldMethod && NewMethod &&
Richard Smith21c8fa82013-01-14 05:37:29 +00001053 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1054 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1055 if (!UseUsingDeclRules &&
1056 (OldMethod->getRefQualifier() == RQ_None ||
1057 NewMethod->getRefQualifier() == RQ_None)) {
1058 // C++0x [over.load]p2:
1059 // - Member function declarations with the same name and the same
1060 // parameter-type-list as well as member function template
1061 // declarations with the same name, the same parameter-type-list, and
1062 // the same template parameter lists cannot be overloaded if any of
1063 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithaa4bc182013-06-30 09:48:50 +00001064 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith21c8fa82013-01-14 05:37:29 +00001065 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithaa4bc182013-06-30 09:48:50 +00001066 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith21c8fa82013-01-14 05:37:29 +00001067 }
1068 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +00001069 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001070
Richard Smith21c8fa82013-01-14 05:37:29 +00001071 // We may not have applied the implicit const for a constexpr member
1072 // function yet (because we haven't yet resolved whether this is a static
1073 // or non-static member function). Add it now, on the assumption that this
1074 // is a redeclaration of OldMethod.
David Majnemer62e93702013-11-03 23:51:28 +00001075 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith21c8fa82013-01-14 05:37:29 +00001076 unsigned NewQuals = NewMethod->getTypeQualifiers();
Richard Smithaa4bc182013-06-30 09:48:50 +00001077 if (!getLangOpts().CPlusPlus1y && NewMethod->isConstexpr() &&
Richard Smithdb2fe732013-06-25 18:46:26 +00001078 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith21c8fa82013-01-14 05:37:29 +00001079 NewQuals |= Qualifiers::Const;
David Majnemer62e93702013-11-03 23:51:28 +00001080
1081 // We do not allow overloading based off of '__restrict'.
1082 OldQuals &= ~Qualifiers::Restrict;
1083 NewQuals &= ~Qualifiers::Restrict;
1084 if (OldQuals != NewQuals)
Richard Smith21c8fa82013-01-14 05:37:29 +00001085 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +00001086 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001087
John McCall68263142009-11-18 22:49:29 +00001088 // The signatures match; this is not an overload.
1089 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001090}
1091
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00001092/// \brief Checks availability of the function depending on the current
1093/// function context. Inside an unavailable function, unavailability is ignored.
1094///
1095/// \returns true if \arg FD is unavailable and current context is inside
1096/// an available function, false otherwise.
1097bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1098 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1099}
1100
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001101/// \brief Tries a user-defined conversion from From to ToType.
1102///
1103/// Produces an implicit conversion sequence for when a standard conversion
1104/// is not an option. See TryImplicitConversion for more information.
1105static ImplicitConversionSequence
1106TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1107 bool SuppressUserConversions,
1108 bool AllowExplicit,
1109 bool InOverloadResolution,
1110 bool CStyle,
Douglas Gregor1ce55092013-11-07 22:34:54 +00001111 bool AllowObjCWritebackConversion,
1112 bool AllowObjCConversionOnExplicit) {
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001113 ImplicitConversionSequence ICS;
1114
1115 if (SuppressUserConversions) {
1116 // We're not in the case above, so there is no conversion that
1117 // we can perform.
1118 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1119 return ICS;
1120 }
1121
1122 // Attempt user-defined conversion.
1123 OverloadCandidateSet Conversions(From->getExprLoc());
1124 OverloadingResult UserDefResult
1125 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor1ce55092013-11-07 22:34:54 +00001126 AllowExplicit, AllowObjCConversionOnExplicit);
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001127
1128 if (UserDefResult == OR_Success) {
1129 ICS.setUserDefined();
1130 // C++ [over.ics.user]p4:
1131 // A conversion of an expression of class type to the same class
1132 // type is given Exact Match rank, and a conversion of an
1133 // expression of class type to a base class of that type is
1134 // given Conversion rank, in spite of the fact that a copy
1135 // constructor (i.e., a user-defined conversion function) is
1136 // called for those cases.
1137 if (CXXConstructorDecl *Constructor
1138 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1139 QualType FromCanon
1140 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1141 QualType ToCanon
1142 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1143 if (Constructor->isCopyConstructor() &&
1144 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1145 // Turn this into a "standard" conversion sequence, so that it
1146 // gets ranked with standard conversion sequences.
1147 ICS.setStandard();
1148 ICS.Standard.setAsIdentityConversion();
1149 ICS.Standard.setFromType(From->getType());
1150 ICS.Standard.setAllToTypes(ToType);
1151 ICS.Standard.CopyConstructor = Constructor;
1152 if (ToCanon != FromCanon)
1153 ICS.Standard.Second = ICK_Derived_To_Base;
1154 }
1155 }
1156
1157 // C++ [over.best.ics]p4:
1158 // However, when considering the argument of a user-defined
1159 // conversion function that is a candidate by 13.3.1.3 when
1160 // invoked for the copying of the temporary in the second step
1161 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1162 // 13.3.1.6 in all cases, only standard conversion sequences and
1163 // ellipsis conversion sequences are allowed.
1164 if (SuppressUserConversions && ICS.isUserDefined()) {
1165 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1166 }
1167 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1168 ICS.setAmbiguous();
1169 ICS.Ambiguous.setFromType(From->getType());
1170 ICS.Ambiguous.setToType(ToType);
1171 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1172 Cand != Conversions.end(); ++Cand)
1173 if (Cand->Viable)
1174 ICS.Ambiguous.addConversion(Cand->Function);
1175 } else {
1176 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1177 }
1178
1179 return ICS;
1180}
1181
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001182/// TryImplicitConversion - Attempt to perform an implicit conversion
1183/// from the given expression (Expr) to the given type (ToType). This
1184/// function returns an implicit conversion sequence that can be used
1185/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001186///
1187/// void f(float f);
1188/// void g(int i) { f(i); }
1189///
1190/// this routine would produce an implicit conversion sequence to
1191/// describe the initialization of f from i, which will be a standard
1192/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1193/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1194//
1195/// Note that this routine only determines how the conversion can be
1196/// performed; it does not actually perform the conversion. As such,
1197/// it will not produce any diagnostics if no conversion is available,
1198/// but will instead return an implicit conversion sequence of kind
1199/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +00001200///
1201/// If @p SuppressUserConversions, then user-defined conversions are
1202/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001203/// If @p AllowExplicit, then explicit user-defined conversions are
1204/// permitted.
John McCallf85e1932011-06-15 23:02:42 +00001205///
1206/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1207/// writeback conversion, which allows __autoreleasing id* parameters to
1208/// be initialized with __strong id* or __weak id* arguments.
John McCall120d63c2010-08-24 20:38:10 +00001209static ImplicitConversionSequence
1210TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1211 bool SuppressUserConversions,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001212 bool AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001213 bool InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001214 bool CStyle,
Douglas Gregor1ce55092013-11-07 22:34:54 +00001215 bool AllowObjCWritebackConversion,
1216 bool AllowObjCConversionOnExplicit) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001217 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +00001218 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001219 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall1d318332010-01-12 00:44:57 +00001220 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +00001221 return ICS;
1222 }
1223
David Blaikie4e4d0842012-03-11 07:00:24 +00001224 if (!S.getLangOpts().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +00001225 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +00001226 return ICS;
1227 }
1228
Douglas Gregor604eb652010-08-11 02:15:33 +00001229 // C++ [over.ics.user]p4:
1230 // A conversion of an expression of class type to the same class
1231 // type is given Exact Match rank, and a conversion of an
1232 // expression of class type to a base class of that type is
1233 // given Conversion rank, in spite of the fact that a copy/move
1234 // constructor (i.e., a user-defined conversion function) is
1235 // called for those cases.
1236 QualType FromType = From->getType();
1237 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00001238 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1239 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001240 ICS.setStandard();
1241 ICS.Standard.setAsIdentityConversion();
1242 ICS.Standard.setFromType(FromType);
1243 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001244
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001245 // We don't actually check at this point whether there is a valid
1246 // copy/move constructor, since overloading just assumes that it
1247 // exists. When we actually perform initialization, we'll find the
1248 // appropriate constructor to copy the returned object, if needed.
1249 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001250
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001251 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +00001252 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001253 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001254
Douglas Gregor604eb652010-08-11 02:15:33 +00001255 return ICS;
1256 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001257
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001258 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1259 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor1ce55092013-11-07 22:34:54 +00001260 AllowObjCWritebackConversion,
1261 AllowObjCConversionOnExplicit);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001262}
1263
John McCallf85e1932011-06-15 23:02:42 +00001264ImplicitConversionSequence
1265Sema::TryImplicitConversion(Expr *From, QualType ToType,
1266 bool SuppressUserConversions,
1267 bool AllowExplicit,
1268 bool InOverloadResolution,
1269 bool CStyle,
1270 bool AllowObjCWritebackConversion) {
1271 return clang::TryImplicitConversion(*this, From, ToType,
1272 SuppressUserConversions, AllowExplicit,
1273 InOverloadResolution, CStyle,
Douglas Gregor1ce55092013-11-07 22:34:54 +00001274 AllowObjCWritebackConversion,
1275 /*AllowObjCConversionOnExplicit=*/false);
John McCall120d63c2010-08-24 20:38:10 +00001276}
1277
Douglas Gregor575c63a2010-04-16 22:27:05 +00001278/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley429bb272011-04-08 18:41:53 +00001279/// expression From to the type ToType. Returns the
Douglas Gregor575c63a2010-04-16 22:27:05 +00001280/// converted expression. Flavor is the kind of conversion we're
1281/// performing, used in the error message. If @p AllowExplicit,
1282/// explicit user-defined conversions are permitted.
John Wiegley429bb272011-04-08 18:41:53 +00001283ExprResult
1284Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001285 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregor575c63a2010-04-16 22:27:05 +00001286 ImplicitConversionSequence ICS;
Sebastian Redl091fffe2011-10-16 18:19:06 +00001287 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001288}
1289
John Wiegley429bb272011-04-08 18:41:53 +00001290ExprResult
1291Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor575c63a2010-04-16 22:27:05 +00001292 AssignmentAction Action, bool AllowExplicit,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001293 ImplicitConversionSequence& ICS) {
John McCall3c3b7f92011-10-25 17:37:35 +00001294 if (checkPlaceholderForOverload(*this, From))
1295 return ExprError();
1296
John McCallf85e1932011-06-15 23:02:42 +00001297 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1298 bool AllowObjCWritebackConversion
David Blaikie4e4d0842012-03-11 07:00:24 +00001299 = getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001300 (Action == AA_Passing || Action == AA_Sending);
John McCallf85e1932011-06-15 23:02:42 +00001301
John McCall120d63c2010-08-24 20:38:10 +00001302 ICS = clang::TryImplicitConversion(*this, From, ToType,
1303 /*SuppressUserConversions=*/false,
1304 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001305 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00001306 /*CStyle=*/false,
Douglas Gregor1ce55092013-11-07 22:34:54 +00001307 AllowObjCWritebackConversion,
1308 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001309 return PerformImplicitConversion(From, ToType, ICS, Action);
1310}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001311
1312/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor43c79c22009-12-09 00:47:37 +00001313/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth18e04612011-06-18 01:19:03 +00001314bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1315 QualType &ResultTy) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001316 if (Context.hasSameUnqualifiedType(FromType, ToType))
1317 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001318
John McCall00ccbef2010-12-21 00:44:39 +00001319 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1320 // where F adds one of the following at most once:
1321 // - a pointer
1322 // - a member pointer
1323 // - a block pointer
1324 CanQualType CanTo = Context.getCanonicalType(ToType);
1325 CanQualType CanFrom = Context.getCanonicalType(FromType);
1326 Type::TypeClass TyClass = CanTo->getTypeClass();
1327 if (TyClass != CanFrom->getTypeClass()) return false;
1328 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1329 if (TyClass == Type::Pointer) {
1330 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1331 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1332 } else if (TyClass == Type::BlockPointer) {
1333 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1334 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1335 } else if (TyClass == Type::MemberPointer) {
1336 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1337 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1338 } else {
1339 return false;
1340 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001341
John McCall00ccbef2010-12-21 00:44:39 +00001342 TyClass = CanTo->getTypeClass();
1343 if (TyClass != CanFrom->getTypeClass()) return false;
1344 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1345 return false;
1346 }
1347
1348 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1349 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1350 if (!EInfo.getNoReturn()) return false;
1351
1352 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1353 assert(QualType(FromFn, 0).isCanonical());
1354 if (QualType(FromFn, 0) != CanTo) return false;
1355
1356 ResultTy = ToType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001357 return true;
1358}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001359
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001360/// \brief Determine whether the conversion from FromType to ToType is a valid
1361/// vector conversion.
1362///
1363/// \param ICK Will be set to the vector conversion kind, if this is a vector
1364/// conversion.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001365static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1366 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001367 // We need at least one of these types to be a vector type to have a vector
1368 // conversion.
1369 if (!ToType->isVectorType() && !FromType->isVectorType())
1370 return false;
1371
1372 // Identical types require no conversions.
1373 if (Context.hasSameUnqualifiedType(FromType, ToType))
1374 return false;
1375
1376 // There are no conversions between extended vector types, only identity.
1377 if (ToType->isExtVectorType()) {
1378 // There are no conversions between extended vector types other than the
1379 // identity conversion.
1380 if (FromType->isExtVectorType())
1381 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001382
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001383 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +00001384 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001385 ICK = ICK_Vector_Splat;
1386 return true;
1387 }
1388 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001389
1390 // We can perform the conversion between vector types in the following cases:
1391 // 1)vector types are equivalent AltiVec and GCC vector types
1392 // 2)lax vector conversions are permitted and the vector types are of the
1393 // same size
1394 if (ToType->isVectorType() && FromType->isVectorType()) {
1395 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
David Blaikie4e4d0842012-03-11 07:00:24 +00001396 (Context.getLangOpts().LaxVectorConversions &&
Chandler Carruthc45eb9c2010-08-08 05:02:51 +00001397 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +00001398 ICK = ICK_Vector_Conversion;
1399 return true;
1400 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001401 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001402
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001403 return false;
1404}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001405
Douglas Gregor7d000652012-04-12 20:48:09 +00001406static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1407 bool InOverloadResolution,
1408 StandardConversionSequence &SCS,
1409 bool CStyle);
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001410
Douglas Gregor60d62c22008-10-31 16:23:19 +00001411/// IsStandardConversion - Determines whether there is a standard
1412/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1413/// expression From to the type ToType. Standard conversion sequences
1414/// only consider non-class types; for conversions that involve class
1415/// types, use TryImplicitConversion. If a conversion exists, SCS will
1416/// contain the standard conversion sequence required to perform this
1417/// conversion and this routine will return true. Otherwise, this
1418/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +00001419static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1420 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001421 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +00001422 bool CStyle,
1423 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001424 QualType FromType = From->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001425
Douglas Gregor60d62c22008-10-31 16:23:19 +00001426 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001427 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +00001428 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +00001429 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +00001430 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +00001431 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001432
Douglas Gregorf9201e02009-02-11 23:02:49 +00001433 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +00001434 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +00001435 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001436 if (S.getLangOpts().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001437 return false;
1438
Mike Stump1eb44332009-09-09 15:08:12 +00001439 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001440 }
1441
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001442 // The first conversion can be an lvalue-to-rvalue conversion,
1443 // array-to-pointer conversion, or function-to-pointer conversion
1444 // (C++ 4p1).
1445
John McCall120d63c2010-08-24 20:38:10 +00001446 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001447 DeclAccessPair AccessPair;
1448 if (FunctionDecl *Fn
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001449 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall120d63c2010-08-24 20:38:10 +00001450 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001451 // We were able to resolve the address of the overloaded function,
1452 // so we can convert to the type of that function.
1453 FromType = Fn->getType();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001454
1455 // we can sometimes resolve &foo<int> regardless of ToType, so check
1456 // if the type matches (identity) or we are converting to bool
1457 if (!S.Context.hasSameUnqualifiedType(
1458 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1459 QualType resultTy;
1460 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth18e04612011-06-18 01:19:03 +00001461 if (!S.IsNoReturnConversion(FromType,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001462 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1463 // otherwise, only a boolean conversion is standard
1464 if (!ToType->isBooleanType())
1465 return false;
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001466 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001467
Chandler Carruth90434232011-03-29 08:08:18 +00001468 // Check if the "from" expression is taking the address of an overloaded
1469 // function and recompute the FromType accordingly. Take advantage of the
1470 // fact that non-static member functions *must* have such an address-of
1471 // expression.
1472 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1473 if (Method && !Method->isStatic()) {
1474 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1475 "Non-unary operator on non-static member address");
1476 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1477 == UO_AddrOf &&
1478 "Non-address-of operator on non-static member address");
1479 const Type *ClassType
1480 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1481 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruthfc5c8fc2011-03-29 18:38:10 +00001482 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1483 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1484 UO_AddrOf &&
Chandler Carruth90434232011-03-29 08:08:18 +00001485 "Non-address-of operator for overloaded function expression");
1486 FromType = S.Context.getPointerType(FromType);
1487 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001488
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001489 // Check that we've computed the proper type after overload resolution.
Chandler Carruth90434232011-03-29 08:08:18 +00001490 assert(S.Context.hasSameType(
1491 FromType,
1492 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001493 } else {
1494 return false;
1495 }
Anders Carlsson2bd62502010-11-04 05:28:09 +00001496 }
John McCall21480112011-08-30 00:57:29 +00001497 // Lvalue-to-rvalue conversion (C++11 4.1):
1498 // A glvalue (3.10) of a non-function, non-array type T can
1499 // be converted to a prvalue.
1500 bool argIsLValue = From->isGLValue();
John McCall7eb0a9e2010-11-24 05:12:34 +00001501 if (argIsLValue &&
Douglas Gregor904eed32008-11-10 20:40:00 +00001502 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +00001503 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001504 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001505
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001506 // C11 6.3.2.1p2:
1507 // ... if the lvalue has atomic type, the value has the non-atomic version
1508 // of the type of the lvalue ...
1509 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1510 FromType = Atomic->getValueType();
1511
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001512 // If T is a non-class type, the type of the rvalue is the
1513 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001514 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1515 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001516 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001517 } else if (FromType->isArrayType()) {
1518 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001519 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001520
1521 // An lvalue or rvalue of type "array of N T" or "array of unknown
1522 // bound of T" can be converted to an rvalue of type "pointer to
1523 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001524 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001525
John McCall120d63c2010-08-24 20:38:10 +00001526 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001527 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001528 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001529
1530 // For the purpose of ranking in overload resolution
1531 // (13.3.3.1.1), this conversion is considered an
1532 // array-to-pointer conversion followed by a qualification
1533 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001534 SCS.Second = ICK_Identity;
1535 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001536 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregorad323a82010-01-27 03:51:04 +00001537 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001538 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001539 }
John McCall7eb0a9e2010-11-24 05:12:34 +00001540 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001541 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001542 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001543
1544 // An lvalue of function type T can be converted to an rvalue of
1545 // type "pointer to T." The result is a pointer to the
1546 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001547 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001548 } else {
1549 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001550 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001551 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001552 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001553
1554 // The second conversion can be an integral promotion, floating
1555 // point promotion, integral conversion, floating point conversion,
1556 // floating-integral conversion, pointer conversion,
1557 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001558 // For overloading in C, this can also be a "compatible-type"
1559 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001560 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001561 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001562 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001563 // The unqualified versions of the types are the same: there's no
1564 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001565 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001566 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001567 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001568 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001569 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001570 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001571 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001572 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001573 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001574 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001575 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001576 SCS.Second = ICK_Complex_Promotion;
1577 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001578 } else if (ToType->isBooleanType() &&
1579 (FromType->isArithmeticType() ||
1580 FromType->isAnyPointerType() ||
1581 FromType->isBlockPointerType() ||
1582 FromType->isMemberPointerType() ||
1583 FromType->isNullPtrType())) {
1584 // Boolean conversions (C++ 4.12).
1585 SCS.Second = ICK_Boolean_Conversion;
1586 FromType = S.Context.BoolTy;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001587 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001588 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001589 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001590 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001591 FromType = ToType.getUnqualifiedType();
Richard Smith42860f12013-05-10 20:29:50 +00001592 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001593 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001594 SCS.Second = ICK_Complex_Conversion;
1595 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001596 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1597 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001598 // Complex-real conversions (C99 6.3.1.7)
1599 SCS.Second = ICK_Complex_Real;
1600 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001601 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001602 // Floating point conversions (C++ 4.8).
1603 SCS.Second = ICK_Floating_Conversion;
1604 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001605 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001606 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001607 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001608 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001609 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001610 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001611 FromType = ToType.getUnqualifiedType();
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001612 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCallf85e1932011-06-15 23:02:42 +00001613 SCS.Second = ICK_Block_Pointer_Conversion;
1614 } else if (AllowObjCWritebackConversion &&
1615 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1616 SCS.Second = ICK_Writeback_Conversion;
John McCall120d63c2010-08-24 20:38:10 +00001617 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1618 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001619 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001620 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001621 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001622 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001623 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall120d63c2010-08-24 20:38:10 +00001624 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001625 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001626 SCS.Second = ICK_Pointer_Member;
John McCall120d63c2010-08-24 20:38:10 +00001627 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001628 SCS.Second = SecondICK;
1629 FromType = ToType.getUnqualifiedType();
David Blaikie4e4d0842012-03-11 07:00:24 +00001630 } else if (!S.getLangOpts().CPlusPlus &&
John McCall120d63c2010-08-24 20:38:10 +00001631 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001632 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001633 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001634 FromType = ToType.getUnqualifiedType();
Chandler Carruth18e04612011-06-18 01:19:03 +00001635 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001636 // Treat a conversion that strips "noreturn" as an identity conversion.
1637 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001638 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1639 InOverloadResolution,
1640 SCS, CStyle)) {
1641 SCS.Second = ICK_TransparentUnionConversion;
1642 FromType = ToType;
Douglas Gregor7d000652012-04-12 20:48:09 +00001643 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1644 CStyle)) {
1645 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001646 // appropriately.
1647 return true;
Guy Benyei6959acd2013-02-07 16:05:33 +00001648 } else if (ToType->isEventT() &&
1649 From->isIntegerConstantExpr(S.getASTContext()) &&
1650 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1651 SCS.Second = ICK_Zero_Event_Conversion;
1652 FromType = ToType;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001653 } else {
1654 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001655 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001656 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001657 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001658
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001659 QualType CanonFrom;
1660 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001661 // The third conversion can be a qualification conversion (C++ 4p1).
John McCallf85e1932011-06-15 23:02:42 +00001662 bool ObjCLifetimeConversion;
1663 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1664 ObjCLifetimeConversion)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001665 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001666 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001667 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001668 CanonFrom = S.Context.getCanonicalType(FromType);
1669 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001670 } else {
1671 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001672 SCS.Third = ICK_Identity;
1673
Mike Stump1eb44332009-09-09 15:08:12 +00001674 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001675 // [...] Any difference in top-level cv-qualification is
1676 // subsumed by the initialization itself and does not constitute
1677 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001678 CanonFrom = S.Context.getCanonicalType(FromType);
1679 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001680 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregora4923eb2009-11-16 21:35:15 +00001681 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault5509f372013-02-26 21:15:54 +00001682 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001683 FromType = ToType;
1684 CanonFrom = CanonTo;
1685 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001686 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001687 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001688
1689 // If we have not converted the argument type to the parameter type,
1690 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001691 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001692 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001693
Douglas Gregor60d62c22008-10-31 16:23:19 +00001694 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001695}
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001696
1697static bool
1698IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1699 QualType &ToType,
1700 bool InOverloadResolution,
1701 StandardConversionSequence &SCS,
1702 bool CStyle) {
1703
1704 const RecordType *UT = ToType->getAsUnionType();
1705 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1706 return false;
1707 // The field to initialize within the transparent union.
1708 RecordDecl *UD = UT->getDecl();
1709 // It's compatible if the expression matches any of the fields.
1710 for (RecordDecl::field_iterator it = UD->field_begin(),
1711 itend = UD->field_end();
1712 it != itend; ++it) {
John McCallf85e1932011-06-15 23:02:42 +00001713 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1714 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001715 ToType = it->getType();
1716 return true;
1717 }
1718 }
1719 return false;
1720}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001721
1722/// IsIntegralPromotion - Determines whether the conversion from the
1723/// expression From (whose potentially-adjusted type is FromType) to
1724/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1725/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001726bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001727 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001728 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001729 if (!To) {
1730 return false;
1731 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001732
1733 // An rvalue of type char, signed char, unsigned char, short int, or
1734 // unsigned short int can be converted to an rvalue of type int if
1735 // int can represent all the values of the source type; otherwise,
1736 // the source rvalue can be converted to an rvalue of type unsigned
1737 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001738 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1739 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001740 if (// We can promote any signed, promotable integer type to an int
1741 (FromType->isSignedIntegerType() ||
1742 // We can promote any unsigned integer type whose size is
1743 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001744 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001745 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001746 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001747 }
1748
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001749 return To->getKind() == BuiltinType::UInt;
1750 }
1751
Richard Smithe7ff9192012-09-13 21:18:54 +00001752 // C++11 [conv.prom]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001753 // A prvalue of an unscoped enumeration type whose underlying type is not
1754 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1755 // following types that can represent all the values of the enumeration
1756 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1757 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001758 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001759 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001760 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001761 // with lowest integer conversion rank (4.13) greater than the rank of long
1762 // long in which all the values of the enumeration can be represented. If
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001763 // there are two such extended types, the signed one is chosen.
Richard Smithe7ff9192012-09-13 21:18:54 +00001764 // C++11 [conv.prom]p4:
1765 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1766 // can be converted to a prvalue of its underlying type. Moreover, if
1767 // integral promotion can be applied to its underlying type, a prvalue of an
1768 // unscoped enumeration type whose underlying type is fixed can also be
1769 // converted to a prvalue of the promoted underlying type.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001770 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1771 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1772 // provided for a scoped enumeration.
1773 if (FromEnumType->getDecl()->isScoped())
1774 return false;
1775
Richard Smithe7ff9192012-09-13 21:18:54 +00001776 // We can perform an integral promotion to the underlying type of the enum,
1777 // even if that's not the promoted type.
1778 if (FromEnumType->getDecl()->isFixed()) {
1779 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1780 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1781 IsIntegralPromotion(From, Underlying, ToType);
1782 }
1783
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001784 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001785 if (ToType->isIntegerType() &&
Douglas Gregord10099e2012-05-04 16:32:21 +00001786 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall842aef82009-12-09 09:09:27 +00001787 return Context.hasSameUnqualifiedType(ToType,
1788 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001789 }
John McCall842aef82009-12-09 09:09:27 +00001790
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001791 // C++0x [conv.prom]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001792 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1793 // to an rvalue a prvalue of the first of the following types that can
1794 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001795 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001796 // If none of the types in that list can represent all the values of its
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001797 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001798 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001799 // type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001800 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001801 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001802 // Determine whether the type we're converting from is signed or
1803 // unsigned.
David Majnemer0ad92312011-07-22 21:09:04 +00001804 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001805 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001806
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001807 // The types we'll try to promote to, in the appropriate
1808 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001809 QualType PromoteTypes[6] = {
1810 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001811 Context.LongTy, Context.UnsignedLongTy ,
1812 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001813 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001814 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001815 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1816 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001817 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001818 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1819 // We found the type that we can promote to. If this is the
1820 // type we wanted, we have a promotion. Otherwise, no
1821 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001822 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001823 }
1824 }
1825 }
1826
1827 // An rvalue for an integral bit-field (9.6) can be converted to an
1828 // rvalue of type int if int can represent all the values of the
1829 // bit-field; otherwise, it can be converted to unsigned int if
1830 // unsigned int can represent all the values of the bit-field. If
1831 // the bit-field is larger yet, no integral promotion applies to
1832 // it. If the bit-field has an enumerated type, it is treated as any
1833 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001834 // FIXME: We should delay checking of bit-fields until we actually perform the
1835 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001836 using llvm::APSInt;
1837 if (From)
John McCall993f43f2013-05-06 21:39:12 +00001838 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001839 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001840 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001841 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1842 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1843 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001844
Douglas Gregor86f19402008-12-20 23:49:58 +00001845 // Are we promoting to an int from a bitfield that fits in an int?
1846 if (BitWidth < ToSize ||
1847 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1848 return To->getKind() == BuiltinType::Int;
1849 }
Mike Stump1eb44332009-09-09 15:08:12 +00001850
Douglas Gregor86f19402008-12-20 23:49:58 +00001851 // Are we promoting to an unsigned int from an unsigned bitfield
1852 // that fits into an unsigned int?
1853 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1854 return To->getKind() == BuiltinType::UInt;
1855 }
Mike Stump1eb44332009-09-09 15:08:12 +00001856
Douglas Gregor86f19402008-12-20 23:49:58 +00001857 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001858 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001859 }
Mike Stump1eb44332009-09-09 15:08:12 +00001860
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001861 // An rvalue of type bool can be converted to an rvalue of type int,
1862 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001863 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001864 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001865 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001866
1867 return false;
1868}
1869
1870/// IsFloatingPointPromotion - Determines whether the conversion from
1871/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1872/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001873bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001874 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1875 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001876 /// An rvalue of type float can be converted to an rvalue of type
1877 /// double. (C++ 4.6p1).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001878 if (FromBuiltin->getKind() == BuiltinType::Float &&
1879 ToBuiltin->getKind() == BuiltinType::Double)
1880 return true;
1881
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001882 // C99 6.3.1.5p1:
1883 // When a float is promoted to double or long double, or a
1884 // double is promoted to long double [...].
David Blaikie4e4d0842012-03-11 07:00:24 +00001885 if (!getLangOpts().CPlusPlus &&
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001886 (FromBuiltin->getKind() == BuiltinType::Float ||
1887 FromBuiltin->getKind() == BuiltinType::Double) &&
1888 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1889 return true;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001890
1891 // Half can be promoted to float.
Joey Gouly19dbb202013-01-23 11:56:20 +00001892 if (!getLangOpts().NativeHalfType &&
1893 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001894 ToBuiltin->getKind() == BuiltinType::Float)
1895 return true;
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001896 }
1897
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001898 return false;
1899}
1900
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001901/// \brief Determine if a conversion is a complex promotion.
1902///
1903/// A complex promotion is defined as a complex -> complex conversion
1904/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001905/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001906bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001907 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001908 if (!FromComplex)
1909 return false;
1910
John McCall183700f2009-09-21 23:43:11 +00001911 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001912 if (!ToComplex)
1913 return false;
1914
1915 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001916 ToComplex->getElementType()) ||
1917 IsIntegralPromotion(0, FromComplex->getElementType(),
1918 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001919}
1920
Douglas Gregorcb7de522008-11-26 23:31:11 +00001921/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1922/// the pointer type FromPtr to a pointer to type ToPointee, with the
1923/// same type qualifiers as FromPtr has on its pointee type. ToType,
1924/// if non-empty, will be a pointer to ToType that may or may not have
1925/// the right set of qualifiers on its pointee.
John McCallf85e1932011-06-15 23:02:42 +00001926///
Mike Stump1eb44332009-09-09 15:08:12 +00001927static QualType
Douglas Gregorda80f742010-12-01 21:43:58 +00001928BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001929 QualType ToPointee, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00001930 ASTContext &Context,
1931 bool StripObjCLifetime = false) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001932 assert((FromPtr->getTypeClass() == Type::Pointer ||
1933 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1934 "Invalid similarly-qualified pointer type");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001935
John McCallf85e1932011-06-15 23:02:42 +00001936 /// Conversions to 'id' subsume cv-qualifier conversions.
1937 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregor143c7ac2010-12-06 22:09:19 +00001938 return ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001939
1940 QualType CanonFromPointee
Douglas Gregorda80f742010-12-01 21:43:58 +00001941 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregorcb7de522008-11-26 23:31:11 +00001942 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001943 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001944
John McCallf85e1932011-06-15 23:02:42 +00001945 if (StripObjCLifetime)
1946 Quals.removeObjCLifetime();
1947
Mike Stump1eb44332009-09-09 15:08:12 +00001948 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001949 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001950 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001951 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001952 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001953
1954 // Build a pointer to ToPointee. It has the right qualifiers
1955 // already.
Douglas Gregorda80f742010-12-01 21:43:58 +00001956 if (isa<ObjCObjectPointerType>(ToType))
1957 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregorcb7de522008-11-26 23:31:11 +00001958 return Context.getPointerType(ToPointee);
1959 }
1960
1961 // Just build a canonical type that has the right qualifiers.
Douglas Gregorda80f742010-12-01 21:43:58 +00001962 QualType QualifiedCanonToPointee
1963 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001964
Douglas Gregorda80f742010-12-01 21:43:58 +00001965 if (isa<ObjCObjectPointerType>(ToType))
1966 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1967 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001968}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001969
Mike Stump1eb44332009-09-09 15:08:12 +00001970static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001971 bool InOverloadResolution,
1972 ASTContext &Context) {
1973 // Handle value-dependent integral null pointer constants correctly.
1974 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1975 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001976 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001977 return !InOverloadResolution;
1978
Douglas Gregorce940492009-09-25 04:25:58 +00001979 return Expr->isNullPointerConstant(Context,
1980 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1981 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001982}
Mike Stump1eb44332009-09-09 15:08:12 +00001983
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001984/// IsPointerConversion - Determines whether the conversion of the
1985/// expression From, which has the (possibly adjusted) type FromType,
1986/// can be converted to the type ToType via a pointer conversion (C++
1987/// 4.10). If so, returns true and places the converted type (that
1988/// might differ from ToType in its cv-qualifiers at some level) into
1989/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001990///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001991/// This routine also supports conversions to and from block pointers
1992/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1993/// pointers to interfaces. FIXME: Once we've determined the
1994/// appropriate overloading rules for Objective-C, we may want to
1995/// split the Objective-C checks into a different routine; however,
1996/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001997/// conversions, so for now they live here. IncompatibleObjC will be
1998/// set if the conversion is an allowed Objective-C conversion that
1999/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002000bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00002001 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00002002 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00002003 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00002004 IncompatibleObjC = false;
Chandler Carruth6df868e2010-12-12 08:17:55 +00002005 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2006 IncompatibleObjC))
Douglas Gregorc7887512008-12-19 19:13:09 +00002007 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00002008
Mike Stump1eb44332009-09-09 15:08:12 +00002009 // Conversion from a null pointer constant to any Objective-C pointer type.
2010 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002011 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00002012 ConvertedType = ToType;
2013 return true;
2014 }
2015
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002016 // Blocks: Block pointers can be converted to void*.
2017 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002018 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002019 ConvertedType = ToType;
2020 return true;
2021 }
2022 // Blocks: A null pointer constant can be converted to a block
2023 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00002024 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002025 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002026 ConvertedType = ToType;
2027 return true;
2028 }
2029
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002030 // If the left-hand-side is nullptr_t, the right side can be a null
2031 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00002032 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002033 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002034 ConvertedType = ToType;
2035 return true;
2036 }
2037
Ted Kremenek6217b802009-07-29 21:53:49 +00002038 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002039 if (!ToTypePtr)
2040 return false;
2041
2042 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002043 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002044 ConvertedType = ToType;
2045 return true;
2046 }
Sebastian Redl07779722008-10-31 14:43:28 +00002047
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002048 // Beyond this point, both types need to be pointers
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002049 // , including objective-c pointers.
2050 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002051 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002052 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002053 ConvertedType = BuildSimilarlyQualifiedPointerType(
2054 FromType->getAs<ObjCObjectPointerType>(),
2055 ToPointeeType,
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002056 ToType, Context);
2057 return true;
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002058 }
Ted Kremenek6217b802009-07-29 21:53:49 +00002059 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002060 if (!FromTypePtr)
2061 return false;
2062
2063 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002064
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002065 // If the unqualified pointee types are the same, this can't be a
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00002066 // pointer conversion, so don't do all of the work below.
2067 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2068 return false;
2069
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002070 // An rvalue of type "pointer to cv T," where T is an object type,
2071 // can be converted to an rvalue of type "pointer to cv void" (C++
2072 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00002073 if (FromPointeeType->isIncompleteOrObjectType() &&
2074 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002075 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002076 ToPointeeType,
John McCallf85e1932011-06-15 23:02:42 +00002077 ToType, Context,
2078 /*StripObjCLifetime=*/true);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002079 return true;
2080 }
2081
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002082 // MSVC allows implicit function to void* type conversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002083 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002084 ToPointeeType->isVoidType()) {
2085 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2086 ToPointeeType,
2087 ToType, Context);
2088 return true;
2089 }
2090
Douglas Gregorf9201e02009-02-11 23:02:49 +00002091 // When we're overloading in C, we allow a special kind of pointer
2092 // conversion for compatible-but-not-identical pointee types.
David Blaikie4e4d0842012-03-11 07:00:24 +00002093 if (!getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002094 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002095 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00002096 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00002097 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00002098 return true;
2099 }
2100
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002101 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00002102 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002103 // An rvalue of type "pointer to cv D," where D is a class type,
2104 // can be converted to an rvalue of type "pointer to cv B," where
2105 // B is a base class (clause 10) of D. If B is an inaccessible
2106 // (clause 11) or ambiguous (10.2) base class of D, a program that
2107 // necessitates this conversion is ill-formed. The result of the
2108 // conversion is a pointer to the base class sub-object of the
2109 // derived class object. The null pointer value is converted to
2110 // the null pointer value of the destination type.
2111 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002112 // Note that we do not check for ambiguity or inaccessibility
2113 // here. That is handled by CheckPointerConversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002114 if (getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002115 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00002116 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002117 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00002118 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002119 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002120 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002121 ToType, Context);
2122 return true;
2123 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002124
Fariborz Jahanian5da3c082011-04-14 20:33:36 +00002125 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2126 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2127 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2128 ToPointeeType,
2129 ToType, Context);
2130 return true;
2131 }
2132
Douglas Gregorc7887512008-12-19 19:13:09 +00002133 return false;
2134}
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002135
2136/// \brief Adopt the given qualifiers for the given type.
2137static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2138 Qualifiers TQs = T.getQualifiers();
2139
2140 // Check whether qualifiers already match.
2141 if (TQs == Qs)
2142 return T;
2143
2144 if (Qs.compatiblyIncludes(TQs))
2145 return Context.getQualifiedType(T, Qs);
2146
2147 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2148}
Douglas Gregorc7887512008-12-19 19:13:09 +00002149
2150/// isObjCPointerConversion - Determines whether this is an
2151/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2152/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00002153bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00002154 QualType& ConvertedType,
2155 bool &IncompatibleObjC) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002156 if (!getLangOpts().ObjC1)
Douglas Gregorc7887512008-12-19 19:13:09 +00002157 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002158
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002159 // The set of qualifiers on the type we're converting from.
2160 Qualifiers FromQualifiers = FromType.getQualifiers();
2161
Steve Naroff14108da2009-07-10 23:34:53 +00002162 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth6df868e2010-12-12 08:17:55 +00002163 const ObjCObjectPointerType* ToObjCPtr =
2164 ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002165 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00002166 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002167
Steve Naroff14108da2009-07-10 23:34:53 +00002168 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002169 // If the pointee types are the same (ignoring qualifications),
2170 // then this is not a pointer conversion.
2171 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2172 FromObjCPtr->getPointeeType()))
2173 return false;
2174
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002175 // Check for compatible
Steve Naroffde2e22d2009-07-15 18:40:39 +00002176 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00002177 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00002178 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002179 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002180 return true;
2181 }
2182 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00002183 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00002184 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00002185 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00002186 /*compare=*/false)) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002187 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002188 return true;
2189 }
2190 // Objective C++: We're able to convert from a pointer to an
2191 // interface to a pointer to a different interface.
2192 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002193 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2194 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002195 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002196 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2197 FromObjCPtr->getPointeeType()))
2198 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002199 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002200 ToObjCPtr->getPointeeType(),
2201 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002202 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002203 return true;
2204 }
2205
2206 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2207 // Okay: this is some kind of implicit downcast of Objective-C
2208 // interfaces, which is permitted. However, we're going to
2209 // complain about it.
2210 IncompatibleObjC = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002211 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002212 ToObjCPtr->getPointeeType(),
2213 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002214 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002215 return true;
2216 }
Mike Stump1eb44332009-09-09 15:08:12 +00002217 }
Steve Naroff14108da2009-07-10 23:34:53 +00002218 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002219 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002220 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002221 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002222 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002223 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00002224 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002225 // to a block pointer type.
2226 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002227 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002228 return true;
2229 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002230 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002231 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002232 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002233 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002234 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00002235 // pointer to any object.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002236 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002237 return true;
2238 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002239 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002240 return false;
2241
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002242 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002243 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002244 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth6df868e2010-12-12 08:17:55 +00002245 else if (const BlockPointerType *FromBlockPtr =
2246 FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002247 FromPointeeType = FromBlockPtr->getPointeeType();
2248 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002249 return false;
2250
Douglas Gregorc7887512008-12-19 19:13:09 +00002251 // If we have pointers to pointers, recursively check whether this
2252 // is an Objective-C conversion.
2253 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2254 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2255 IncompatibleObjC)) {
2256 // We always complain about this conversion.
2257 IncompatibleObjC = true;
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);
Douglas Gregorc7887512008-12-19 19:13:09 +00002260 return true;
2261 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002262 // Allow conversion of pointee being objective-c pointer to another one;
2263 // as in I* to id.
2264 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2265 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2266 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2267 IncompatibleObjC)) {
John McCallf85e1932011-06-15 23:02:42 +00002268
Douglas Gregorda80f742010-12-01 21:43:58 +00002269 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002270 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002271 return true;
2272 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002273
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002274 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00002275 // differences in the argument and result types are in Objective-C
2276 // pointer conversions. If so, we permit the conversion (but
2277 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00002278 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00002279 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00002280 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00002281 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002282 if (FromFunctionType && ToFunctionType) {
2283 // If the function types are exactly the same, this isn't an
2284 // Objective-C pointer conversion.
2285 if (Context.getCanonicalType(FromPointeeType)
2286 == Context.getCanonicalType(ToPointeeType))
2287 return false;
2288
2289 // Perform the quick checks that will tell us whether these
2290 // function types are obviously different.
2291 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2292 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2293 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2294 return false;
2295
2296 bool HasObjCConversion = false;
2297 if (Context.getCanonicalType(FromFunctionType->getResultType())
2298 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2299 // Okay, the types match exactly. Nothing to do.
2300 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2301 ToFunctionType->getResultType(),
2302 ConvertedType, IncompatibleObjC)) {
2303 // Okay, we have an Objective-C pointer conversion.
2304 HasObjCConversion = true;
2305 } else {
2306 // Function types are too different. Abort.
2307 return false;
2308 }
Mike Stump1eb44332009-09-09 15:08:12 +00002309
Douglas Gregorc7887512008-12-19 19:13:09 +00002310 // Check argument types.
2311 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2312 ArgIdx != NumArgs; ++ArgIdx) {
2313 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2314 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2315 if (Context.getCanonicalType(FromArgType)
2316 == Context.getCanonicalType(ToArgType)) {
2317 // Okay, the types match exactly. Nothing to do.
2318 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2319 ConvertedType, IncompatibleObjC)) {
2320 // Okay, we have an Objective-C pointer conversion.
2321 HasObjCConversion = true;
2322 } else {
2323 // Argument types are too different. Abort.
2324 return false;
2325 }
2326 }
2327
2328 if (HasObjCConversion) {
2329 // We had an Objective-C conversion. Allow this pointer
2330 // conversion, but complain about it.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002331 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002332 IncompatibleObjC = true;
2333 return true;
2334 }
2335 }
2336
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002337 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002338}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002339
John McCallf85e1932011-06-15 23:02:42 +00002340/// \brief Determine whether this is an Objective-C writeback conversion,
2341/// used for parameter passing when performing automatic reference counting.
2342///
2343/// \param FromType The type we're converting form.
2344///
2345/// \param ToType The type we're converting to.
2346///
2347/// \param ConvertedType The type that will be produced after applying
2348/// this conversion.
2349bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2350 QualType &ConvertedType) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002351 if (!getLangOpts().ObjCAutoRefCount ||
John McCallf85e1932011-06-15 23:02:42 +00002352 Context.hasSameUnqualifiedType(FromType, ToType))
2353 return false;
2354
2355 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2356 QualType ToPointee;
2357 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2358 ToPointee = ToPointer->getPointeeType();
2359 else
2360 return false;
2361
2362 Qualifiers ToQuals = ToPointee.getQualifiers();
2363 if (!ToPointee->isObjCLifetimeType() ||
2364 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall200fa532012-02-08 00:46:36 +00002365 !ToQuals.withoutObjCLifetime().empty())
John McCallf85e1932011-06-15 23:02:42 +00002366 return false;
2367
2368 // Argument must be a pointer to __strong to __weak.
2369 QualType FromPointee;
2370 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2371 FromPointee = FromPointer->getPointeeType();
2372 else
2373 return false;
2374
2375 Qualifiers FromQuals = FromPointee.getQualifiers();
2376 if (!FromPointee->isObjCLifetimeType() ||
2377 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2378 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2379 return false;
2380
2381 // Make sure that we have compatible qualifiers.
2382 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2383 if (!ToQuals.compatiblyIncludes(FromQuals))
2384 return false;
2385
2386 // Remove qualifiers from the pointee type we're converting from; they
2387 // aren't used in the compatibility check belong, and we'll be adding back
2388 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2389 FromPointee = FromPointee.getUnqualifiedType();
2390
2391 // The unqualified form of the pointee types must be compatible.
2392 ToPointee = ToPointee.getUnqualifiedType();
2393 bool IncompatibleObjC;
2394 if (Context.typesAreCompatible(FromPointee, ToPointee))
2395 FromPointee = ToPointee;
2396 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2397 IncompatibleObjC))
2398 return false;
2399
2400 /// \brief Construct the type we're converting to, which is a pointer to
2401 /// __autoreleasing pointee.
2402 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2403 ConvertedType = Context.getPointerType(FromPointee);
2404 return true;
2405}
2406
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002407bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2408 QualType& ConvertedType) {
2409 QualType ToPointeeType;
2410 if (const BlockPointerType *ToBlockPtr =
2411 ToType->getAs<BlockPointerType>())
2412 ToPointeeType = ToBlockPtr->getPointeeType();
2413 else
2414 return false;
2415
2416 QualType FromPointeeType;
2417 if (const BlockPointerType *FromBlockPtr =
2418 FromType->getAs<BlockPointerType>())
2419 FromPointeeType = FromBlockPtr->getPointeeType();
2420 else
2421 return false;
2422 // We have pointer to blocks, check whether the only
2423 // differences in the argument and result types are in Objective-C
2424 // pointer conversions. If so, we permit the conversion.
2425
2426 const FunctionProtoType *FromFunctionType
2427 = FromPointeeType->getAs<FunctionProtoType>();
2428 const FunctionProtoType *ToFunctionType
2429 = ToPointeeType->getAs<FunctionProtoType>();
2430
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002431 if (!FromFunctionType || !ToFunctionType)
2432 return false;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002433
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002434 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002435 return true;
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002436
2437 // Perform the quick checks that will tell us whether these
2438 // function types are obviously different.
2439 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2440 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2441 return false;
2442
2443 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2444 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2445 if (FromEInfo != ToEInfo)
2446 return false;
2447
2448 bool IncompatibleObjC = false;
Fariborz Jahanian462dae52011-02-13 20:11:42 +00002449 if (Context.hasSameType(FromFunctionType->getResultType(),
2450 ToFunctionType->getResultType())) {
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002451 // Okay, the types match exactly. Nothing to do.
2452 } else {
2453 QualType RHS = FromFunctionType->getResultType();
2454 QualType LHS = ToFunctionType->getResultType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002455 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002456 !RHS.hasQualifiers() && LHS.hasQualifiers())
2457 LHS = LHS.getUnqualifiedType();
2458
2459 if (Context.hasSameType(RHS,LHS)) {
2460 // OK exact match.
2461 } else if (isObjCPointerConversion(RHS, LHS,
2462 ConvertedType, IncompatibleObjC)) {
2463 if (IncompatibleObjC)
2464 return false;
2465 // Okay, we have an Objective-C pointer conversion.
2466 }
2467 else
2468 return false;
2469 }
2470
2471 // Check argument types.
2472 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2473 ArgIdx != NumArgs; ++ArgIdx) {
2474 IncompatibleObjC = false;
2475 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2476 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2477 if (Context.hasSameType(FromArgType, ToArgType)) {
2478 // Okay, the types match exactly. Nothing to do.
2479 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2480 ConvertedType, IncompatibleObjC)) {
2481 if (IncompatibleObjC)
2482 return false;
2483 // Okay, we have an Objective-C pointer conversion.
2484 } else
2485 // Argument types are too different. Abort.
2486 return false;
2487 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00002488 if (LangOpts.ObjCAutoRefCount &&
2489 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2490 ToFunctionType))
2491 return false;
Fariborz Jahanianf9d95272011-09-28 20:22:05 +00002492
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002493 ConvertedType = ToType;
2494 return true;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002495}
2496
Richard Trieu6efd4c52011-11-23 22:32:32 +00002497enum {
2498 ft_default,
2499 ft_different_class,
2500 ft_parameter_arity,
2501 ft_parameter_mismatch,
2502 ft_return_type,
2503 ft_qualifer_mismatch
2504};
2505
2506/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2507/// function types. Catches different number of parameter, mismatch in
2508/// parameter types, and different return types.
2509void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2510 QualType FromType, QualType ToType) {
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002511 // If either type is not valid, include no extra info.
2512 if (FromType.isNull() || ToType.isNull()) {
2513 PDiag << ft_default;
2514 return;
2515 }
2516
Richard Trieu6efd4c52011-11-23 22:32:32 +00002517 // Get the function type from the pointers.
2518 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2519 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2520 *ToMember = ToType->getAs<MemberPointerType>();
2521 if (FromMember->getClass() != ToMember->getClass()) {
2522 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2523 << QualType(FromMember->getClass(), 0);
2524 return;
2525 }
2526 FromType = FromMember->getPointeeType();
2527 ToType = ToMember->getPointeeType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00002528 }
2529
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002530 if (FromType->isPointerType())
2531 FromType = FromType->getPointeeType();
2532 if (ToType->isPointerType())
2533 ToType = ToType->getPointeeType();
2534
2535 // Remove references.
Richard Trieu6efd4c52011-11-23 22:32:32 +00002536 FromType = FromType.getNonReferenceType();
2537 ToType = ToType.getNonReferenceType();
2538
Richard Trieu6efd4c52011-11-23 22:32:32 +00002539 // Don't print extra info for non-specialized template functions.
2540 if (FromType->isInstantiationDependentType() &&
2541 !FromType->getAs<TemplateSpecializationType>()) {
2542 PDiag << ft_default;
2543 return;
2544 }
2545
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002546 // No extra info for same types.
2547 if (Context.hasSameType(FromType, ToType)) {
2548 PDiag << ft_default;
2549 return;
2550 }
2551
Richard Trieu6efd4c52011-11-23 22:32:32 +00002552 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2553 *ToFunction = ToType->getAs<FunctionProtoType>();
2554
2555 // Both types need to be function types.
2556 if (!FromFunction || !ToFunction) {
2557 PDiag << ft_default;
2558 return;
2559 }
2560
2561 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2562 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2563 << FromFunction->getNumArgs();
2564 return;
2565 }
2566
2567 // Handle different parameter types.
2568 unsigned ArgPos;
2569 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2570 PDiag << ft_parameter_mismatch << ArgPos + 1
2571 << ToFunction->getArgType(ArgPos)
2572 << FromFunction->getArgType(ArgPos);
2573 return;
2574 }
2575
2576 // Handle different return type.
2577 if (!Context.hasSameType(FromFunction->getResultType(),
2578 ToFunction->getResultType())) {
2579 PDiag << ft_return_type << ToFunction->getResultType()
2580 << FromFunction->getResultType();
2581 return;
2582 }
2583
2584 unsigned FromQuals = FromFunction->getTypeQuals(),
2585 ToQuals = ToFunction->getTypeQuals();
2586 if (FromQuals != ToQuals) {
2587 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2588 return;
2589 }
2590
2591 // Unable to find a difference, so add no extra info.
2592 PDiag << ft_default;
2593}
2594
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002595/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregordec1cc42011-12-15 17:15:07 +00002596/// for equality of their argument types. Caller has already checked that
Eli Friedman06017002013-06-18 22:41:37 +00002597/// they have same number of arguments. If the parameters are different,
2598/// ArgPos will have the parameter index of the first different parameter.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002599bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieu6efd4c52011-11-23 22:32:32 +00002600 const FunctionProtoType *NewType,
2601 unsigned *ArgPos) {
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002602 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2603 N = NewType->arg_type_begin(),
2604 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
Richard Trieu7ea491c2013-08-09 21:42:32 +00002605 if (!Context.hasSameType(O->getUnqualifiedType(),
2606 N->getUnqualifiedType())) {
Larisse Voufo3151b7c2013-08-06 03:57:41 +00002607 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2608 return false;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002609 }
2610 }
2611 return true;
2612}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002613
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002614/// CheckPointerConversion - Check the pointer conversion from the
2615/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002616/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002617/// conversions for which IsPointerConversion has already returned
2618/// true. It returns true and produces a diagnostic if there was an
2619/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00002620bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002621 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002622 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002623 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002624 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00002625 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002626
John McCalldaa8e4e2010-11-15 09:13:47 +00002627 Kind = CK_BitCast;
2628
David Blaikie50800fc2012-08-08 17:33:31 +00002629 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2630 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2631 Expr::NPCK_ZeroExpression) {
2632 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2633 DiagRuntimeBehavior(From->getExprLoc(), From,
2634 PDiag(diag::warn_impcast_bool_to_null_pointer)
2635 << ToType << From->getSourceRange());
2636 else if (!isUnevaluatedContext())
2637 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2638 << ToType << From->getSourceRange();
2639 }
John McCall1d9b3b22011-09-09 05:25:32 +00002640 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2641 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002642 QualType FromPointeeType = FromPtrType->getPointeeType(),
2643 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00002644
Douglas Gregor5fccd362010-03-03 23:55:11 +00002645 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2646 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002647 // We must have a derived-to-base conversion. Check an
2648 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00002649 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2650 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002651 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002652 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00002653 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002654
Anders Carlsson61faec12009-09-12 04:46:44 +00002655 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00002656 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002657 }
2658 }
John McCall1d9b3b22011-09-09 05:25:32 +00002659 } else if (const ObjCObjectPointerType *ToPtrType =
2660 ToType->getAs<ObjCObjectPointerType>()) {
2661 if (const ObjCObjectPointerType *FromPtrType =
2662 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002663 // Objective-C++ conversions are always okay.
2664 // FIXME: We should have a different class of conversions for the
2665 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00002666 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00002667 return false;
John McCall1d9b3b22011-09-09 05:25:32 +00002668 } else if (FromType->isBlockPointerType()) {
2669 Kind = CK_BlockPointerToObjCPointerCast;
2670 } else {
2671 Kind = CK_CPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00002672 }
John McCall1d9b3b22011-09-09 05:25:32 +00002673 } else if (ToType->isBlockPointerType()) {
2674 if (!FromType->isBlockPointerType())
2675 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00002676 }
John McCalldaa8e4e2010-11-15 09:13:47 +00002677
2678 // We shouldn't fall into this case unless it's valid for other
2679 // reasons.
2680 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2681 Kind = CK_NullToPointer;
2682
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002683 return false;
2684}
2685
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002686/// IsMemberPointerConversion - Determines whether the conversion of the
2687/// expression From, which has the (possibly adjusted) type FromType, can be
2688/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2689/// If so, returns true and places the converted type (that might differ from
2690/// ToType in its cv-qualifiers at some level) into ConvertedType.
2691bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002692 QualType ToType,
Douglas Gregorce940492009-09-25 04:25:58 +00002693 bool InOverloadResolution,
2694 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002695 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002696 if (!ToTypePtr)
2697 return false;
2698
2699 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00002700 if (From->isNullPointerConstant(Context,
2701 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2702 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002703 ConvertedType = ToType;
2704 return true;
2705 }
2706
2707 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00002708 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002709 if (!FromTypePtr)
2710 return false;
2711
2712 // A pointer to member of B can be converted to a pointer to member of D,
2713 // where D is derived from B (C++ 4.11p2).
2714 QualType FromClass(FromTypePtr->getClass(), 0);
2715 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002716
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002717 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002718 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002719 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002720 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2721 ToClass.getTypePtr());
2722 return true;
2723 }
2724
2725 return false;
2726}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002727
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002728/// CheckMemberPointerConversion - Check the member pointer conversion from the
2729/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00002730/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002731/// for which IsMemberPointerConversion has already returned true. It returns
2732/// true and produces a diagnostic if there was an error, or returns false
2733/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002734bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002735 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002736 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002737 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002738 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002739 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002740 if (!FromPtrType) {
2741 // This must be a null pointer to member pointer conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002742 assert(From->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00002743 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002744 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00002745 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002746 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002747 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002748
Ted Kremenek6217b802009-07-29 21:53:49 +00002749 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00002750 assert(ToPtrType && "No member pointer cast has a target type "
2751 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002752
Sebastian Redl21593ac2009-01-28 18:33:18 +00002753 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2754 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002755
Sebastian Redl21593ac2009-01-28 18:33:18 +00002756 // FIXME: What about dependent types?
2757 assert(FromClass->isRecordType() && "Pointer into non-class.");
2758 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002759
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002760 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002761 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00002762 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2763 assert(DerivationOkay &&
2764 "Should not have been called if derivation isn't OK.");
2765 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002766
Sebastian Redl21593ac2009-01-28 18:33:18 +00002767 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2768 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002769 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2770 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2771 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2772 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002773 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00002774
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002775 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002776 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2777 << FromClass << ToClass << QualType(VBase, 0)
2778 << From->getSourceRange();
2779 return true;
2780 }
2781
John McCall6b2accb2010-02-10 09:31:12 +00002782 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00002783 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2784 Paths.front(),
2785 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00002786
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002787 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002788 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00002789 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002790 return false;
2791}
2792
Douglas Gregor3940e3b2013-11-08 02:04:24 +00002793/// Determine whether the lifetime conversion between the two given
2794/// qualifiers sets is nontrivial.
2795static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2796 Qualifiers ToQuals) {
2797 // Converting anything to const __unsafe_unretained is trivial.
2798 if (ToQuals.hasConst() &&
2799 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2800 return false;
2801
2802 return true;
2803}
2804
Douglas Gregor98cd5992008-10-21 23:43:52 +00002805/// IsQualificationConversion - Determines whether the conversion from
2806/// an rvalue of type FromType to ToType is a qualification conversion
2807/// (C++ 4.4).
John McCallf85e1932011-06-15 23:02:42 +00002808///
2809/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2810/// when the qualification conversion involves a change in the Objective-C
2811/// object lifetime.
Mike Stump1eb44332009-09-09 15:08:12 +00002812bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002813Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00002814 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002815 FromType = Context.getCanonicalType(FromType);
2816 ToType = Context.getCanonicalType(ToType);
John McCallf85e1932011-06-15 23:02:42 +00002817 ObjCLifetimeConversion = false;
2818
Douglas Gregor98cd5992008-10-21 23:43:52 +00002819 // If FromType and ToType are the same type, this is not a
2820 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00002821 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00002822 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002823
Douglas Gregor98cd5992008-10-21 23:43:52 +00002824 // (C++ 4.4p4):
2825 // A conversion can add cv-qualifiers at levels other than the first
2826 // in multi-level pointers, subject to the following rules: [...]
2827 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002828 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002829 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002830 // Within each iteration of the loop, we check the qualifiers to
2831 // determine if this still looks like a qualification
2832 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002833 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00002834 // until there are no more pointers or pointers-to-members left to
2835 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00002836 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002837
Douglas Gregor621c92a2011-04-25 18:40:17 +00002838 Qualifiers FromQuals = FromType.getQualifiers();
2839 Qualifiers ToQuals = ToType.getQualifiers();
2840
John McCallf85e1932011-06-15 23:02:42 +00002841 // Objective-C ARC:
2842 // Check Objective-C lifetime conversions.
2843 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2844 UnwrappedAnyPointer) {
2845 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregor3940e3b2013-11-08 02:04:24 +00002846 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2847 ObjCLifetimeConversion = true;
John McCallf85e1932011-06-15 23:02:42 +00002848 FromQuals.removeObjCLifetime();
2849 ToQuals.removeObjCLifetime();
2850 } else {
2851 // Qualification conversions cannot cast between different
2852 // Objective-C lifetime qualifiers.
2853 return false;
2854 }
2855 }
2856
Douglas Gregor377e1bd2011-05-08 06:09:53 +00002857 // Allow addition/removal of GC attributes but not changing GC attributes.
2858 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2859 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2860 FromQuals.removeObjCGCAttr();
2861 ToQuals.removeObjCGCAttr();
2862 }
2863
Douglas Gregor98cd5992008-10-21 23:43:52 +00002864 // -- for every j > 0, if const is in cv 1,j then const is in cv
2865 // 2,j, and similarly for volatile.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002866 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002867 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002868
Douglas Gregor98cd5992008-10-21 23:43:52 +00002869 // -- if the cv 1,j and cv 2,j are different, then const is in
2870 // every cv for 0 < k < j.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002871 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00002872 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00002873 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002874
Douglas Gregor98cd5992008-10-21 23:43:52 +00002875 // Keep track of whether all prior cv-qualifiers in the "to" type
2876 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00002877 PreviousToQualsIncludeConst
Douglas Gregor621c92a2011-04-25 18:40:17 +00002878 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregor57373262008-10-22 14:17:15 +00002879 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00002880
2881 // We are left with FromType and ToType being the pointee types
2882 // after unwrapping the original FromType and ToType the same number
2883 // of types. If we unwrapped any pointers, and if FromType and
2884 // ToType have the same unqualified type (since we checked
2885 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002886 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00002887}
2888
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002889/// \brief - Determine whether this is a conversion from a scalar type to an
2890/// atomic type.
2891///
2892/// If successful, updates \c SCS's second and third steps in the conversion
2893/// sequence to finish the conversion.
Douglas Gregor7d000652012-04-12 20:48:09 +00002894static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2895 bool InOverloadResolution,
2896 StandardConversionSequence &SCS,
2897 bool CStyle) {
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002898 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2899 if (!ToAtomic)
2900 return false;
2901
2902 StandardConversionSequence InnerSCS;
2903 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2904 InOverloadResolution, InnerSCS,
2905 CStyle, /*AllowObjCWritebackConversion=*/false))
2906 return false;
2907
2908 SCS.Second = InnerSCS.Second;
2909 SCS.setToType(1, InnerSCS.getToType(1));
2910 SCS.Third = InnerSCS.Third;
2911 SCS.QualificationIncludesObjCLifetime
2912 = InnerSCS.QualificationIncludesObjCLifetime;
2913 SCS.setToType(2, InnerSCS.getToType(2));
2914 return true;
2915}
2916
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002917static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2918 CXXConstructorDecl *Constructor,
2919 QualType Type) {
2920 const FunctionProtoType *CtorType =
2921 Constructor->getType()->getAs<FunctionProtoType>();
2922 if (CtorType->getNumArgs() > 0) {
2923 QualType FirstArg = CtorType->getArgType(0);
2924 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2925 return true;
2926 }
2927 return false;
2928}
2929
Sebastian Redl56a04282012-02-11 23:51:08 +00002930static OverloadingResult
2931IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2932 CXXRecordDecl *To,
2933 UserDefinedConversionSequence &User,
2934 OverloadCandidateSet &CandidateSet,
2935 bool AllowExplicit) {
David Blaikie3bc93e32012-12-19 00:45:41 +00002936 DeclContext::lookup_result R = S.LookupConstructors(To);
2937 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl56a04282012-02-11 23:51:08 +00002938 Con != ConEnd; ++Con) {
2939 NamedDecl *D = *Con;
2940 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2941
2942 // Find the constructor (which may be a template).
2943 CXXConstructorDecl *Constructor = 0;
2944 FunctionTemplateDecl *ConstructorTmpl
2945 = dyn_cast<FunctionTemplateDecl>(D);
2946 if (ConstructorTmpl)
2947 Constructor
2948 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2949 else
2950 Constructor = cast<CXXConstructorDecl>(D);
2951
2952 bool Usable = !Constructor->isInvalidDecl() &&
2953 S.isInitListConstructor(Constructor) &&
2954 (AllowExplicit || !Constructor->isExplicit());
2955 if (Usable) {
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002956 // If the first argument is (a reference to) the target type,
2957 // suppress conversions.
2958 bool SuppressUserConversions =
2959 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl56a04282012-02-11 23:51:08 +00002960 if (ConstructorTmpl)
2961 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2962 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002963 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002964 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002965 else
2966 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002967 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002968 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002969 }
2970 }
2971
2972 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2973
2974 OverloadCandidateSet::iterator Best;
2975 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2976 case OR_Success: {
2977 // Record the standard conversion we used and the conversion function.
2978 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl56a04282012-02-11 23:51:08 +00002979 QualType ThisType = Constructor->getThisType(S.Context);
2980 // Initializer lists don't have conversions as such.
2981 User.Before.setAsIdentityConversion();
2982 User.HadMultipleCandidates = HadMultipleCandidates;
2983 User.ConversionFunction = Constructor;
2984 User.FoundConversionFunction = Best->FoundDecl;
2985 User.After.setAsIdentityConversion();
2986 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2987 User.After.setAllToTypes(ToType);
2988 return OR_Success;
2989 }
2990
2991 case OR_No_Viable_Function:
2992 return OR_No_Viable_Function;
2993 case OR_Deleted:
2994 return OR_Deleted;
2995 case OR_Ambiguous:
2996 return OR_Ambiguous;
2997 }
2998
2999 llvm_unreachable("Invalid OverloadResult!");
3000}
3001
Douglas Gregor734d9862009-01-30 23:27:23 +00003002/// Determines whether there is a user-defined conversion sequence
3003/// (C++ [over.ics.user]) that converts expression From to the type
3004/// ToType. If such a conversion exists, User will contain the
3005/// user-defined conversion sequence that performs such a conversion
3006/// and this routine will return true. Otherwise, this routine returns
3007/// false and User is unspecified.
3008///
Douglas Gregor734d9862009-01-30 23:27:23 +00003009/// \param AllowExplicit true if the conversion should consider C++0x
3010/// "explicit" conversion functions as well as non-explicit conversion
3011/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor1ce55092013-11-07 22:34:54 +00003012///
3013/// \param AllowObjCConversionOnExplicit true if the conversion should
3014/// allow an extra Objective-C pointer conversion on uses of explicit
3015/// constructors. Requires \c AllowExplicit to also be set.
John McCall120d63c2010-08-24 20:38:10 +00003016static OverloadingResult
3017IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl56a04282012-02-11 23:51:08 +00003018 UserDefinedConversionSequence &User,
3019 OverloadCandidateSet &CandidateSet,
Douglas Gregor1ce55092013-11-07 22:34:54 +00003020 bool AllowExplicit,
3021 bool AllowObjCConversionOnExplicit) {
Douglas Gregora1977bf2013-11-08 01:20:25 +00003022 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor1ce55092013-11-07 22:34:54 +00003023
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003024 // Whether we will only visit constructors.
3025 bool ConstructorsOnly = false;
3026
3027 // If the type we are conversion to is a class type, enumerate its
3028 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00003029 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003030 // C++ [over.match.ctor]p1:
3031 // When objects of class type are direct-initialized (8.5), or
3032 // copy-initialized from an expression of the same or a
3033 // derived class type (8.5), overload resolution selects the
3034 // constructor. [...] For copy-initialization, the candidate
3035 // functions are all the converting constructors (12.3.1) of
3036 // that class. The argument list is the expression-list within
3037 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00003038 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003039 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00003040 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003041 ConstructorsOnly = true;
3042
Benjamin Kramer63b6ebe2012-11-23 17:04:52 +00003043 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidise36bca62011-04-22 17:45:37 +00003044 // RequireCompleteType may have returned true due to some invalid decl
3045 // during template instantiation, but ToType may be complete enough now
3046 // to try to recover.
3047 if (ToType->isIncompleteType()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00003048 // We're not going to find any constructors.
3049 } else if (CXXRecordDecl *ToRecordDecl
3050 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003051
3052 Expr **Args = &From;
3053 unsigned NumArgs = 1;
3054 bool ListInitializing = false;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003055 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramere5753592013-09-09 14:48:42 +00003056 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl56a04282012-02-11 23:51:08 +00003057 OverloadingResult Result = IsInitializerListConstructorConversion(
3058 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3059 if (Result != OR_No_Viable_Function)
3060 return Result;
3061 // Never mind.
3062 CandidateSet.clear();
3063
3064 // If we're list-initializing, we pass the individual elements as
3065 // arguments, not the entire list.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003066 Args = InitList->getInits();
3067 NumArgs = InitList->getNumInits();
3068 ListInitializing = true;
3069 }
3070
David Blaikie3bc93e32012-12-19 00:45:41 +00003071 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3072 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003073 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00003074 NamedDecl *D = *Con;
3075 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3076
Douglas Gregordec06662009-08-21 18:42:58 +00003077 // Find the constructor (which may be a template).
3078 CXXConstructorDecl *Constructor = 0;
3079 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00003080 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00003081 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00003082 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00003083 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3084 else
John McCall9aa472c2010-03-19 07:35:19 +00003085 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003086
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003087 bool Usable = !Constructor->isInvalidDecl();
3088 if (ListInitializing)
3089 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3090 else
3091 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3092 if (Usable) {
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003093 bool SuppressUserConversions = !ConstructorsOnly;
3094 if (SuppressUserConversions && ListInitializing) {
3095 SuppressUserConversions = false;
3096 if (NumArgs == 1) {
3097 // If the first argument is (a reference to) the target type,
3098 // suppress conversions.
Sebastian Redlf78c0f92012-03-27 18:33:03 +00003099 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3100 S.Context, Constructor, ToType);
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003101 }
3102 }
Douglas Gregordec06662009-08-21 18:42:58 +00003103 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00003104 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3105 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003106 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003107 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003108 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00003109 // Allow one user-defined conversion when user specifies a
3110 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00003111 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003112 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003113 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003114 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003115 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003116 }
3117 }
3118
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003119 // Enumerate conversion functions, if we're allowed to.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003120 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003121 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003122 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00003123 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003124 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003125 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003126 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3127 // Add all of the conversion functions as candidates.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003128 std::pair<CXXRecordDecl::conversion_iterator,
3129 CXXRecordDecl::conversion_iterator>
3130 Conversions = FromRecordDecl->getVisibleConversionFunctions();
3131 for (CXXRecordDecl::conversion_iterator
3132 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00003133 DeclAccessPair FoundDecl = I.getPair();
3134 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003135 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3136 if (isa<UsingShadowDecl>(D))
3137 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3138
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003139 CXXConversionDecl *Conv;
3140 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00003141 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3142 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003143 else
John McCall32daa422010-03-31 01:36:47 +00003144 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003145
3146 if (AllowExplicit || !Conv->isExplicit()) {
3147 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00003148 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3149 ActingContext, From, ToType,
Douglas Gregor1ce55092013-11-07 22:34:54 +00003150 CandidateSet,
3151 AllowObjCConversionOnExplicit);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003152 else
John McCall120d63c2010-08-24 20:38:10 +00003153 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor1ce55092013-11-07 22:34:54 +00003154 From, ToType, CandidateSet,
3155 AllowObjCConversionOnExplicit);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003156 }
3157 }
3158 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003159 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003160
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003161 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3162
Douglas Gregor60d62c22008-10-31 16:23:19 +00003163 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003164 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00003165 case OR_Success:
3166 // Record the standard conversion we used and the conversion function.
3167 if (CXXConstructorDecl *Constructor
3168 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3169 // C++ [over.ics.user]p1:
3170 // If the user-defined conversion is specified by a
3171 // constructor (12.3.1), the initial standard conversion
3172 // sequence converts the source type to the type required by
3173 // the argument of the constructor.
3174 //
3175 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003176 if (isa<InitListExpr>(From)) {
3177 // Initializer lists don't have conversions as such.
3178 User.Before.setAsIdentityConversion();
3179 } else {
3180 if (Best->Conversions[0].isEllipsis())
3181 User.EllipsisConversion = true;
3182 else {
3183 User.Before = Best->Conversions[0].Standard;
3184 User.EllipsisConversion = false;
3185 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003186 }
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003187 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003188 User.ConversionFunction = Constructor;
John McCallca82a822011-09-21 08:36:56 +00003189 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003190 User.After.setAsIdentityConversion();
3191 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3192 User.After.setAllToTypes(ToType);
3193 return OR_Success;
David Blaikie7530c032012-01-17 06:56:22 +00003194 }
3195 if (CXXConversionDecl *Conversion
John McCall120d63c2010-08-24 20:38:10 +00003196 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3197 // C++ [over.ics.user]p1:
3198 //
3199 // [...] If the user-defined conversion is specified by a
3200 // conversion function (12.3.2), the initial standard
3201 // conversion sequence converts the source type to the
3202 // implicit object parameter of the conversion function.
3203 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003204 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003205 User.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00003206 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003207 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003208
John McCall120d63c2010-08-24 20:38:10 +00003209 // C++ [over.ics.user]p2:
3210 // The second standard conversion sequence converts the
3211 // result of the user-defined conversion to the target type
3212 // for the sequence. Since an implicit conversion sequence
3213 // is an initialization, the special rules for
3214 // initialization by user-defined conversion apply when
3215 // selecting the best user-defined conversion for a
3216 // user-defined conversion sequence (see 13.3.3 and
3217 // 13.3.3.1).
3218 User.After = Best->FinalConversion;
3219 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00003220 }
David Blaikie7530c032012-01-17 06:56:22 +00003221 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003222
John McCall120d63c2010-08-24 20:38:10 +00003223 case OR_No_Viable_Function:
3224 return OR_No_Viable_Function;
3225 case OR_Deleted:
3226 // No conversion here! We're done.
3227 return OR_Deleted;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003228
John McCall120d63c2010-08-24 20:38:10 +00003229 case OR_Ambiguous:
3230 return OR_Ambiguous;
3231 }
3232
David Blaikie7530c032012-01-17 06:56:22 +00003233 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003234}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003235
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003236bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003237Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003238 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00003239 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003240 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00003241 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor1ce55092013-11-07 22:34:54 +00003242 CandidateSet, false, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003243 if (OvResult == OR_Ambiguous)
Daniel Dunbar96a00142012-03-09 18:35:03 +00003244 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003245 diag::err_typecheck_ambiguous_condition)
3246 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo7419d012013-06-27 01:50:25 +00003247 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo288f76a2013-06-27 03:36:30 +00003248 if (!RequireCompleteType(From->getLocStart(), ToType,
Larisse Voufo7419d012013-06-27 01:50:25 +00003249 diag::err_typecheck_nonviable_condition_incomplete,
3250 From->getType(), From->getSourceRange()))
3251 Diag(From->getLocStart(),
3252 diag::err_typecheck_nonviable_condition)
3253 << From->getType() << From->getSourceRange() << ToType;
3254 }
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003255 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003256 return false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003257 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003258 return true;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003259}
Douglas Gregor60d62c22008-10-31 16:23:19 +00003260
Douglas Gregorb734e242012-02-22 17:32:19 +00003261/// \brief Compare the user-defined conversion functions or constructors
3262/// of two user-defined conversion sequences to determine whether any ordering
3263/// is possible.
3264static ImplicitConversionSequence::CompareKind
3265compareConversionFunctions(Sema &S,
3266 FunctionDecl *Function1,
3267 FunctionDecl *Function2) {
Richard Smith80ad52f2013-01-02 11:42:31 +00003268 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregorb734e242012-02-22 17:32:19 +00003269 return ImplicitConversionSequence::Indistinguishable;
3270
3271 // Objective-C++:
3272 // If both conversion functions are implicitly-declared conversions from
3273 // a lambda closure type to a function pointer and a block pointer,
3274 // respectively, always prefer the conversion to a function pointer,
3275 // because the function pointer is more lightweight and is more likely
3276 // to keep code working.
3277 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3278 if (!Conv1)
3279 return ImplicitConversionSequence::Indistinguishable;
3280
3281 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3282 if (!Conv2)
3283 return ImplicitConversionSequence::Indistinguishable;
3284
3285 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3286 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3287 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3288 if (Block1 != Block2)
3289 return Block1? ImplicitConversionSequence::Worse
3290 : ImplicitConversionSequence::Better;
3291 }
3292
3293 return ImplicitConversionSequence::Indistinguishable;
3294}
3295
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003296/// CompareImplicitConversionSequences - Compare two implicit
3297/// conversion sequences to determine whether one is better than the
3298/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00003299static ImplicitConversionSequence::CompareKind
3300CompareImplicitConversionSequences(Sema &S,
3301 const ImplicitConversionSequence& ICS1,
3302 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003303{
3304 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3305 // conversion sequences (as defined in 13.3.3.1)
3306 // -- a standard conversion sequence (13.3.3.1.1) is a better
3307 // conversion sequence than a user-defined conversion sequence or
3308 // an ellipsis conversion sequence, and
3309 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3310 // conversion sequence than an ellipsis conversion sequence
3311 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00003312 //
John McCall1d318332010-01-12 00:44:57 +00003313 // C++0x [over.best.ics]p10:
3314 // For the purpose of ranking implicit conversion sequences as
3315 // described in 13.3.3.2, the ambiguous conversion sequence is
3316 // treated as a user-defined sequence that is indistinguishable
3317 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003318 if (ICS1.getKindRank() < ICS2.getKindRank())
3319 return ImplicitConversionSequence::Better;
David Blaikie7530c032012-01-17 06:56:22 +00003320 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003321 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003322
Benjamin Kramerb6eee072010-04-18 12:05:54 +00003323 // The following checks require both conversion sequences to be of
3324 // the same kind.
3325 if (ICS1.getKind() != ICS2.getKind())
3326 return ImplicitConversionSequence::Indistinguishable;
3327
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003328 ImplicitConversionSequence::CompareKind Result =
3329 ImplicitConversionSequence::Indistinguishable;
3330
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003331 // Two implicit conversion sequences of the same form are
3332 // indistinguishable conversion sequences unless one of the
3333 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00003334 if (ICS1.isStandard())
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003335 Result = CompareStandardConversionSequences(S,
3336 ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00003337 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003338 // User-defined conversion sequence U1 is a better conversion
3339 // sequence than another user-defined conversion sequence U2 if
3340 // they contain the same user-defined conversion function or
3341 // constructor and if the second standard conversion sequence of
3342 // U1 is better than the second standard conversion sequence of
3343 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00003344 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003345 ICS2.UserDefined.ConversionFunction)
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003346 Result = CompareStandardConversionSequences(S,
3347 ICS1.UserDefined.After,
3348 ICS2.UserDefined.After);
Douglas Gregorb734e242012-02-22 17:32:19 +00003349 else
3350 Result = compareConversionFunctions(S,
3351 ICS1.UserDefined.ConversionFunction,
3352 ICS2.UserDefined.ConversionFunction);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003353 }
3354
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003355 // List-initialization sequence L1 is a better conversion sequence than
3356 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3357 // for some X and L2 does not.
3358 if (Result == ImplicitConversionSequence::Indistinguishable &&
Richard Smith798186a2013-09-06 22:30:28 +00003359 !ICS1.isBad()) {
Sebastian Redladfb5352012-02-27 22:38:26 +00003360 if (ICS1.isStdInitializerListElement() &&
3361 !ICS2.isStdInitializerListElement())
3362 return ImplicitConversionSequence::Better;
3363 if (!ICS1.isStdInitializerListElement() &&
3364 ICS2.isStdInitializerListElement())
3365 return ImplicitConversionSequence::Worse;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003366 }
3367
3368 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003369}
3370
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003371static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3372 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3373 Qualifiers Quals;
3374 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003375 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003376 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003377
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003378 return Context.hasSameUnqualifiedType(T1, T2);
3379}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003380
Douglas Gregorad323a82010-01-27 03:51:04 +00003381// Per 13.3.3.2p3, compare the given standard conversion sequences to
3382// determine if one is a proper subset of the other.
3383static ImplicitConversionSequence::CompareKind
3384compareStandardConversionSubsets(ASTContext &Context,
3385 const StandardConversionSequence& SCS1,
3386 const StandardConversionSequence& SCS2) {
3387 ImplicitConversionSequence::CompareKind Result
3388 = ImplicitConversionSequence::Indistinguishable;
3389
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003390 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregorae65f4b2010-05-23 22:10:15 +00003391 // any non-identity conversion sequence
Douglas Gregor4ae5b722011-06-05 06:15:20 +00003392 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3393 return ImplicitConversionSequence::Better;
3394 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3395 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003396
Douglas Gregorad323a82010-01-27 03:51:04 +00003397 if (SCS1.Second != SCS2.Second) {
3398 if (SCS1.Second == ICK_Identity)
3399 Result = ImplicitConversionSequence::Better;
3400 else if (SCS2.Second == ICK_Identity)
3401 Result = ImplicitConversionSequence::Worse;
3402 else
3403 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003404 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00003405 return ImplicitConversionSequence::Indistinguishable;
3406
3407 if (SCS1.Third == SCS2.Third) {
3408 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3409 : ImplicitConversionSequence::Indistinguishable;
3410 }
3411
3412 if (SCS1.Third == ICK_Identity)
3413 return Result == ImplicitConversionSequence::Worse
3414 ? ImplicitConversionSequence::Indistinguishable
3415 : ImplicitConversionSequence::Better;
3416
3417 if (SCS2.Third == ICK_Identity)
3418 return Result == ImplicitConversionSequence::Better
3419 ? ImplicitConversionSequence::Indistinguishable
3420 : ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003421
Douglas Gregorad323a82010-01-27 03:51:04 +00003422 return ImplicitConversionSequence::Indistinguishable;
3423}
3424
Douglas Gregor440a4832011-01-26 14:52:12 +00003425/// \brief Determine whether one of the given reference bindings is better
3426/// than the other based on what kind of bindings they are.
3427static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3428 const StandardConversionSequence &SCS2) {
3429 // C++0x [over.ics.rank]p3b4:
3430 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3431 // implicit object parameter of a non-static member function declared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003432 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregor440a4832011-01-26 14:52:12 +00003433 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003434 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregor440a4832011-01-26 14:52:12 +00003435 // reference*.
3436 //
3437 // FIXME: Rvalue references. We're going rogue with the above edits,
3438 // because the semantics in the current C++0x working paper (N3225 at the
3439 // time of this writing) break the standard definition of std::forward
3440 // and std::reference_wrapper when dealing with references to functions.
3441 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003442 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3443 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3444 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003445
Douglas Gregor440a4832011-01-26 14:52:12 +00003446 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3447 SCS2.IsLvalueReference) ||
3448 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3449 !SCS2.IsLvalueReference);
3450}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003451
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003452/// CompareStandardConversionSequences - Compare two standard
3453/// conversion sequences to determine whether one is better than the
3454/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00003455static ImplicitConversionSequence::CompareKind
3456CompareStandardConversionSequences(Sema &S,
3457 const StandardConversionSequence& SCS1,
3458 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003459{
3460 // Standard conversion sequence S1 is a better conversion sequence
3461 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3462
3463 // -- S1 is a proper subsequence of S2 (comparing the conversion
3464 // sequences in the canonical form defined by 13.3.3.1.1,
3465 // excluding any Lvalue Transformation; the identity conversion
3466 // sequence is considered to be a subsequence of any
3467 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00003468 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00003469 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00003470 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003471
3472 // -- the rank of S1 is better than the rank of S2 (by the rules
3473 // defined below), or, if not that,
3474 ImplicitConversionRank Rank1 = SCS1.getRank();
3475 ImplicitConversionRank Rank2 = SCS2.getRank();
3476 if (Rank1 < Rank2)
3477 return ImplicitConversionSequence::Better;
3478 else if (Rank2 < Rank1)
3479 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003480
Douglas Gregor57373262008-10-22 14:17:15 +00003481 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3482 // are indistinguishable unless one of the following rules
3483 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00003484
Douglas Gregor57373262008-10-22 14:17:15 +00003485 // A conversion that is not a conversion of a pointer, or
3486 // pointer to member, to bool is better than another conversion
3487 // that is such a conversion.
3488 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3489 return SCS2.isPointerConversionToBool()
3490 ? ImplicitConversionSequence::Better
3491 : ImplicitConversionSequence::Worse;
3492
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003493 // C++ [over.ics.rank]p4b2:
3494 //
3495 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003496 // conversion of B* to A* is better than conversion of B* to
3497 // void*, and conversion of A* to void* is better than conversion
3498 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00003499 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003500 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003501 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003502 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003503 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3504 // Exactly one of the conversion sequences is a conversion to
3505 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003506 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3507 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003508 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3509 // Neither conversion sequence converts to a void pointer; compare
3510 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003511 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00003512 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003513 return DerivedCK;
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003514 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3515 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003516 // Both conversion sequences are conversions to void
3517 // pointers. Compare the source types to determine if there's an
3518 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00003519 QualType FromType1 = SCS1.getFromType();
3520 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003521
3522 // Adjust the types we're converting from via the array-to-pointer
3523 // conversion, if we need to.
3524 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003525 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003526 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003527 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003528
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003529 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3530 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003531
John McCall120d63c2010-08-24 20:38:10 +00003532 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00003533 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003534 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00003535 return ImplicitConversionSequence::Worse;
3536
3537 // Objective-C++: If one interface is more specific than the
3538 // other, it is the better one.
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003539 const ObjCObjectPointerType* FromObjCPtr1
3540 = FromType1->getAs<ObjCObjectPointerType>();
3541 const ObjCObjectPointerType* FromObjCPtr2
3542 = FromType2->getAs<ObjCObjectPointerType>();
3543 if (FromObjCPtr1 && FromObjCPtr2) {
3544 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3545 FromObjCPtr2);
3546 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3547 FromObjCPtr1);
3548 if (AssignLeft != AssignRight) {
3549 return AssignLeft? ImplicitConversionSequence::Better
3550 : ImplicitConversionSequence::Worse;
3551 }
Douglas Gregor01919692009-12-13 21:37:05 +00003552 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003553 }
Douglas Gregor57373262008-10-22 14:17:15 +00003554
3555 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3556 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00003557 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00003558 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003559 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00003560
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003561 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregor440a4832011-01-26 14:52:12 +00003562 // Check for a better reference binding based on the kind of bindings.
3563 if (isBetterReferenceBindingKind(SCS1, SCS2))
3564 return ImplicitConversionSequence::Better;
3565 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3566 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003567
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003568 // C++ [over.ics.rank]p3b4:
3569 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3570 // which the references refer are the same type except for
3571 // top-level cv-qualifiers, and the type to which the reference
3572 // initialized by S2 refers is more cv-qualified than the type
3573 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00003574 QualType T1 = SCS1.getToType(2);
3575 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003576 T1 = S.Context.getCanonicalType(T1);
3577 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003578 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003579 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3580 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003581 if (UnqualT1 == UnqualT2) {
John McCallf85e1932011-06-15 23:02:42 +00003582 // Objective-C++ ARC: If the references refer to objects with different
3583 // lifetimes, prefer bindings that don't change lifetime.
3584 if (SCS1.ObjCLifetimeConversionBinding !=
3585 SCS2.ObjCLifetimeConversionBinding) {
3586 return SCS1.ObjCLifetimeConversionBinding
3587 ? ImplicitConversionSequence::Worse
3588 : ImplicitConversionSequence::Better;
3589 }
3590
Chandler Carruth6df868e2010-12-12 08:17:55 +00003591 // If the type is an array type, promote the element qualifiers to the
3592 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003593 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003594 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003595 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003596 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003597 if (T2.isMoreQualifiedThan(T1))
3598 return ImplicitConversionSequence::Better;
3599 else if (T1.isMoreQualifiedThan(T2))
John McCallf85e1932011-06-15 23:02:42 +00003600 return ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003601 }
3602 }
Douglas Gregor57373262008-10-22 14:17:15 +00003603
Francois Pichet1c98d622011-09-18 21:37:37 +00003604 // In Microsoft mode, prefer an integral conversion to a
3605 // floating-to-integral conversion if the integral conversion
3606 // is between types of the same size.
3607 // For example:
3608 // void f(float);
3609 // void f(int);
3610 // int main {
3611 // long a;
3612 // f(a);
3613 // }
3614 // Here, MSVC will call f(int) instead of generating a compile error
3615 // as clang will do in standard mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00003616 if (S.getLangOpts().MicrosoftMode &&
Francois Pichet1c98d622011-09-18 21:37:37 +00003617 SCS1.Second == ICK_Integral_Conversion &&
3618 SCS2.Second == ICK_Floating_Integral &&
3619 S.Context.getTypeSize(SCS1.getFromType()) ==
3620 S.Context.getTypeSize(SCS1.getToType(2)))
3621 return ImplicitConversionSequence::Better;
3622
Douglas Gregor57373262008-10-22 14:17:15 +00003623 return ImplicitConversionSequence::Indistinguishable;
3624}
3625
3626/// CompareQualificationConversions - Compares two standard conversion
3627/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00003628/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3629ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003630CompareQualificationConversions(Sema &S,
3631 const StandardConversionSequence& SCS1,
3632 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00003633 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00003634 // -- S1 and S2 differ only in their qualification conversion and
3635 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3636 // cv-qualification signature of type T1 is a proper subset of
3637 // the cv-qualification signature of type T2, and S1 is not the
3638 // deprecated string literal array-to-pointer conversion (4.2).
3639 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3640 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3641 return ImplicitConversionSequence::Indistinguishable;
3642
3643 // FIXME: the example in the standard doesn't use a qualification
3644 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00003645 QualType T1 = SCS1.getToType(2);
3646 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003647 T1 = S.Context.getCanonicalType(T1);
3648 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003649 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003650 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3651 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00003652
3653 // If the types are the same, we won't learn anything by unwrapped
3654 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003655 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00003656 return ImplicitConversionSequence::Indistinguishable;
3657
Chandler Carruth28e318c2009-12-29 07:16:59 +00003658 // If the type is an array type, promote the element qualifiers to the type
3659 // for comparison.
3660 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003661 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003662 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003663 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003664
Mike Stump1eb44332009-09-09 15:08:12 +00003665 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00003666 = ImplicitConversionSequence::Indistinguishable;
John McCallf85e1932011-06-15 23:02:42 +00003667
3668 // Objective-C++ ARC:
3669 // Prefer qualification conversions not involving a change in lifetime
3670 // to qualification conversions that do not change lifetime.
3671 if (SCS1.QualificationIncludesObjCLifetime !=
3672 SCS2.QualificationIncludesObjCLifetime) {
3673 Result = SCS1.QualificationIncludesObjCLifetime
3674 ? ImplicitConversionSequence::Worse
3675 : ImplicitConversionSequence::Better;
3676 }
3677
John McCall120d63c2010-08-24 20:38:10 +00003678 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00003679 // Within each iteration of the loop, we check the qualifiers to
3680 // determine if this still looks like a qualification
3681 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00003682 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00003683 // until there are no more pointers or pointers-to-members left
3684 // to unwrap. This essentially mimics what
3685 // IsQualificationConversion does, but here we're checking for a
3686 // strict subset of qualifiers.
3687 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3688 // The qualifiers are the same, so this doesn't tell us anything
3689 // about how the sequences rank.
3690 ;
3691 else if (T2.isMoreQualifiedThan(T1)) {
3692 // T1 has fewer qualifiers, so it could be the better sequence.
3693 if (Result == ImplicitConversionSequence::Worse)
3694 // Neither has qualifiers that are a subset of the other's
3695 // qualifiers.
3696 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003697
Douglas Gregor57373262008-10-22 14:17:15 +00003698 Result = ImplicitConversionSequence::Better;
3699 } else if (T1.isMoreQualifiedThan(T2)) {
3700 // T2 has fewer qualifiers, so it could be the better sequence.
3701 if (Result == ImplicitConversionSequence::Better)
3702 // Neither has qualifiers that are a subset of the other's
3703 // qualifiers.
3704 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003705
Douglas Gregor57373262008-10-22 14:17:15 +00003706 Result = ImplicitConversionSequence::Worse;
3707 } else {
3708 // Qualifiers are disjoint.
3709 return ImplicitConversionSequence::Indistinguishable;
3710 }
3711
3712 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00003713 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00003714 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003715 }
3716
Douglas Gregor57373262008-10-22 14:17:15 +00003717 // Check that the winning standard conversion sequence isn't using
3718 // the deprecated string literal array to pointer conversion.
3719 switch (Result) {
3720 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00003721 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003722 Result = ImplicitConversionSequence::Indistinguishable;
3723 break;
3724
3725 case ImplicitConversionSequence::Indistinguishable:
3726 break;
3727
3728 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00003729 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003730 Result = ImplicitConversionSequence::Indistinguishable;
3731 break;
3732 }
3733
3734 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003735}
3736
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003737/// CompareDerivedToBaseConversions - Compares two standard conversion
3738/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00003739/// various kinds of derived-to-base conversions (C++
3740/// [over.ics.rank]p4b3). As part of these checks, we also look at
3741/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003742ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003743CompareDerivedToBaseConversions(Sema &S,
3744 const StandardConversionSequence& SCS1,
3745 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00003746 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003747 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00003748 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003749 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003750
3751 // Adjust the types we're converting from via the array-to-pointer
3752 // conversion, if we need to.
3753 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003754 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003755 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003756 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003757
3758 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00003759 FromType1 = S.Context.getCanonicalType(FromType1);
3760 ToType1 = S.Context.getCanonicalType(ToType1);
3761 FromType2 = S.Context.getCanonicalType(FromType2);
3762 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003763
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003764 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003765 //
3766 // If class B is derived directly or indirectly from class A and
3767 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00003768 //
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003769 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00003770 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00003771 SCS2.Second == ICK_Pointer_Conversion &&
3772 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3773 FromType1->isPointerType() && FromType2->isPointerType() &&
3774 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003775 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003776 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00003777 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003778 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003779 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003780 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003781 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003782 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00003783
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003784 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003785 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003786 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003787 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003788 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003789 return ImplicitConversionSequence::Worse;
3790 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003791
3792 // -- conversion of B* to A* is better than conversion of C* to A*,
3793 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003794 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003795 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003796 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003797 return ImplicitConversionSequence::Worse;
Douglas Gregor395cc372011-01-31 18:51:41 +00003798 }
3799 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3800 SCS2.Second == ICK_Pointer_Conversion) {
3801 const ObjCObjectPointerType *FromPtr1
3802 = FromType1->getAs<ObjCObjectPointerType>();
3803 const ObjCObjectPointerType *FromPtr2
3804 = FromType2->getAs<ObjCObjectPointerType>();
3805 const ObjCObjectPointerType *ToPtr1
3806 = ToType1->getAs<ObjCObjectPointerType>();
3807 const ObjCObjectPointerType *ToPtr2
3808 = ToType2->getAs<ObjCObjectPointerType>();
3809
3810 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3811 // Apply the same conversion ranking rules for Objective-C pointer types
3812 // that we do for C++ pointers to class types. However, we employ the
3813 // Objective-C pseudo-subtyping relationship used for assignment of
3814 // Objective-C pointer types.
3815 bool FromAssignLeft
3816 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3817 bool FromAssignRight
3818 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3819 bool ToAssignLeft
3820 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3821 bool ToAssignRight
3822 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3823
3824 // A conversion to an a non-id object pointer type or qualified 'id'
3825 // type is better than a conversion to 'id'.
3826 if (ToPtr1->isObjCIdType() &&
3827 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3828 return ImplicitConversionSequence::Worse;
3829 if (ToPtr2->isObjCIdType() &&
3830 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3831 return ImplicitConversionSequence::Better;
3832
3833 // A conversion to a non-id object pointer type is better than a
3834 // conversion to a qualified 'id' type
3835 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3836 return ImplicitConversionSequence::Worse;
3837 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3838 return ImplicitConversionSequence::Better;
3839
3840 // A conversion to an a non-Class object pointer type or qualified 'Class'
3841 // type is better than a conversion to 'Class'.
3842 if (ToPtr1->isObjCClassType() &&
3843 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3844 return ImplicitConversionSequence::Worse;
3845 if (ToPtr2->isObjCClassType() &&
3846 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3847 return ImplicitConversionSequence::Better;
3848
3849 // A conversion to a non-Class object pointer type is better than a
3850 // conversion to a qualified 'Class' type.
3851 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3852 return ImplicitConversionSequence::Worse;
3853 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3854 return ImplicitConversionSequence::Better;
Mike Stump1eb44332009-09-09 15:08:12 +00003855
Douglas Gregor395cc372011-01-31 18:51:41 +00003856 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3857 if (S.Context.hasSameType(FromType1, FromType2) &&
3858 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3859 (ToAssignLeft != ToAssignRight))
3860 return ToAssignLeft? ImplicitConversionSequence::Worse
3861 : ImplicitConversionSequence::Better;
3862
3863 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3864 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3865 (FromAssignLeft != FromAssignRight))
3866 return FromAssignLeft? ImplicitConversionSequence::Better
3867 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003868 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003869 }
Douglas Gregor395cc372011-01-31 18:51:41 +00003870
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003871 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003872 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3873 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3874 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003875 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003876 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003877 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003878 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003879 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003880 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003881 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003882 ToType2->getAs<MemberPointerType>();
3883 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3884 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3885 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3886 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3887 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3888 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3889 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3890 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003891 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003892 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003893 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003894 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00003895 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003896 return ImplicitConversionSequence::Better;
3897 }
3898 // conversion of B::* to C::* is better than conversion of A::* to C::*
3899 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003900 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003901 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003902 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003903 return ImplicitConversionSequence::Worse;
3904 }
3905 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003906
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003907 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00003908 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00003909 // -- binding of an expression of type C to a reference of type
3910 // B& is better than binding an expression of type C to a
3911 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003912 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3913 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3914 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003915 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003916 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003917 return ImplicitConversionSequence::Worse;
3918 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003919
Douglas Gregor225c41e2008-11-03 19:09:14 +00003920 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00003921 // -- binding of an expression of type B to a reference of type
3922 // A& is better than binding an expression of type C to a
3923 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003924 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3925 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3926 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003927 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003928 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003929 return ImplicitConversionSequence::Worse;
3930 }
3931 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003932
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003933 return ImplicitConversionSequence::Indistinguishable;
3934}
3935
Douglas Gregor0162c1c2013-03-26 23:36:30 +00003936/// \brief Determine whether the given type is valid, e.g., it is not an invalid
3937/// C++ class.
3938static bool isTypeValid(QualType T) {
3939 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3940 return !Record->isInvalidDecl();
3941
3942 return true;
3943}
3944
Douglas Gregorabe183d2010-04-13 16:31:36 +00003945/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3946/// determine whether they are reference-related,
3947/// reference-compatible, reference-compatible with added
3948/// qualification, or incompatible, for use in C++ initialization by
3949/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3950/// type, and the first type (T1) is the pointee type of the reference
3951/// type being initialized.
3952Sema::ReferenceCompareResult
3953Sema::CompareReferenceRelationship(SourceLocation Loc,
3954 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00003955 bool &DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003956 bool &ObjCConversion,
3957 bool &ObjCLifetimeConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003958 assert(!OrigT1->isReferenceType() &&
3959 "T1 must be the pointee type of the reference type");
3960 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3961
3962 QualType T1 = Context.getCanonicalType(OrigT1);
3963 QualType T2 = Context.getCanonicalType(OrigT2);
3964 Qualifiers T1Quals, T2Quals;
3965 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3966 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3967
3968 // C++ [dcl.init.ref]p4:
3969 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3970 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3971 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00003972 DerivedToBase = false;
3973 ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003974 ObjCLifetimeConversion = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003975 if (UnqualT1 == UnqualT2) {
3976 // Nothing to do.
Douglas Gregord10099e2012-05-04 16:32:21 +00003977 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor0162c1c2013-03-26 23:36:30 +00003978 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
3979 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregorabe183d2010-04-13 16:31:36 +00003980 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00003981 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3982 UnqualT2->isObjCObjectOrInterfaceType() &&
3983 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3984 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003985 else
3986 return Ref_Incompatible;
3987
3988 // At this point, we know that T1 and T2 are reference-related (at
3989 // least).
3990
3991 // If the type is an array type, promote the element qualifiers to the type
3992 // for comparison.
3993 if (isa<ArrayType>(T1) && T1Quals)
3994 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3995 if (isa<ArrayType>(T2) && T2Quals)
3996 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3997
3998 // C++ [dcl.init.ref]p4:
3999 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4000 // reference-related to T2 and cv1 is the same cv-qualification
4001 // as, or greater cv-qualification than, cv2. For purposes of
4002 // overload resolution, cases for which cv1 is greater
4003 // cv-qualification than cv2 are identified as
4004 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregora6ce3e62011-04-28 17:56:11 +00004005 //
4006 // Note that we also require equivalence of Objective-C GC and address-space
4007 // qualifiers when performing these computations, so that e.g., an int in
4008 // address space 1 is not reference-compatible with an int in address
4009 // space 2.
John McCallf85e1932011-06-15 23:02:42 +00004010 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4011 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregor3940e3b2013-11-08 02:04:24 +00004012 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4013 ObjCLifetimeConversion = true;
4014
John McCallf85e1932011-06-15 23:02:42 +00004015 T1Quals.removeObjCLifetime();
4016 T2Quals.removeObjCLifetime();
John McCallf85e1932011-06-15 23:02:42 +00004017 }
4018
Douglas Gregora6ce3e62011-04-28 17:56:11 +00004019 if (T1Quals == T2Quals)
Douglas Gregorabe183d2010-04-13 16:31:36 +00004020 return Ref_Compatible;
John McCallf85e1932011-06-15 23:02:42 +00004021 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregorabe183d2010-04-13 16:31:36 +00004022 return Ref_Compatible_With_Added_Qualification;
4023 else
4024 return Ref_Related;
4025}
4026
Douglas Gregor604eb652010-08-11 02:15:33 +00004027/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00004028/// with DeclType. Return true if something definite is found.
4029static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00004030FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4031 QualType DeclType, SourceLocation DeclLoc,
4032 Expr *Init, QualType T2, bool AllowRvalues,
4033 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004034 assert(T2->isRecordType() && "Can only find conversions of record types.");
4035 CXXRecordDecl *T2RecordDecl
4036 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4037
4038 OverloadCandidateSet CandidateSet(DeclLoc);
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00004039 std::pair<CXXRecordDecl::conversion_iterator,
4040 CXXRecordDecl::conversion_iterator>
4041 Conversions = T2RecordDecl->getVisibleConversionFunctions();
4042 for (CXXRecordDecl::conversion_iterator
4043 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004044 NamedDecl *D = *I;
4045 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4046 if (isa<UsingShadowDecl>(D))
4047 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4048
4049 FunctionTemplateDecl *ConvTemplate
4050 = dyn_cast<FunctionTemplateDecl>(D);
4051 CXXConversionDecl *Conv;
4052 if (ConvTemplate)
4053 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4054 else
4055 Conv = cast<CXXConversionDecl>(D);
4056
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004057 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor604eb652010-08-11 02:15:33 +00004058 // explicit conversions, skip it.
4059 if (!AllowExplicit && Conv->isExplicit())
4060 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004061
Douglas Gregor604eb652010-08-11 02:15:33 +00004062 if (AllowRvalues) {
4063 bool DerivedToBase = false;
4064 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004065 bool ObjCLifetimeConversion = false;
Douglas Gregor203050c2011-10-04 23:59:32 +00004066
4067 // If we are initializing an rvalue reference, don't permit conversion
4068 // functions that return lvalues.
4069 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4070 const ReferenceType *RefType
4071 = Conv->getConversionType()->getAs<LValueReferenceType>();
4072 if (RefType && !RefType->getPointeeType()->isFunctionType())
4073 continue;
4074 }
4075
Douglas Gregor604eb652010-08-11 02:15:33 +00004076 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00004077 S.CompareReferenceRelationship(
4078 DeclLoc,
4079 Conv->getConversionType().getNonReferenceType()
4080 .getUnqualifiedType(),
4081 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCallf85e1932011-06-15 23:02:42 +00004082 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth6df868e2010-12-12 08:17:55 +00004083 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-08-11 02:15:33 +00004084 continue;
4085 } else {
4086 // If the conversion function doesn't return a reference type,
4087 // it can't be considered for this conversion. An rvalue reference
4088 // is only acceptable if its referencee is a function type.
4089
4090 const ReferenceType *RefType =
4091 Conv->getConversionType()->getAs<ReferenceType>();
4092 if (!RefType ||
4093 (!RefType->isLValueReferenceType() &&
4094 !RefType->getPointeeType()->isFunctionType()))
4095 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004096 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004097
Douglas Gregor604eb652010-08-11 02:15:33 +00004098 if (ConvTemplate)
4099 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor1ce55092013-11-07 22:34:54 +00004100 Init, DeclType, CandidateSet,
4101 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor604eb652010-08-11 02:15:33 +00004102 else
4103 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor1ce55092013-11-07 22:34:54 +00004104 DeclType, CandidateSet,
4105 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl4680bf22010-06-30 18:13:39 +00004106 }
4107
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004108 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4109
Sebastian Redl4680bf22010-06-30 18:13:39 +00004110 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004111 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004112 case OR_Success:
4113 // C++ [over.ics.ref]p1:
4114 //
4115 // [...] If the parameter binds directly to the result of
4116 // applying a conversion function to the argument
4117 // expression, the implicit conversion sequence is a
4118 // user-defined conversion sequence (13.3.3.1.2), with the
4119 // second standard conversion sequence either an identity
4120 // conversion or, if the conversion function returns an
4121 // entity of a type that is a derived class of the parameter
4122 // type, a derived-to-base Conversion.
4123 if (!Best->FinalConversion.DirectBinding)
4124 return false;
4125
4126 ICS.setUserDefined();
4127 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4128 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004129 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004130 ICS.UserDefined.ConversionFunction = Best->Function;
John McCallca82a822011-09-21 08:36:56 +00004131 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004132 ICS.UserDefined.EllipsisConversion = false;
4133 assert(ICS.UserDefined.After.ReferenceBinding &&
4134 ICS.UserDefined.After.DirectBinding &&
4135 "Expected a direct reference binding!");
4136 return true;
4137
4138 case OR_Ambiguous:
4139 ICS.setAmbiguous();
4140 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4141 Cand != CandidateSet.end(); ++Cand)
4142 if (Cand->Viable)
4143 ICS.Ambiguous.addConversion(Cand->Function);
4144 return true;
4145
4146 case OR_No_Viable_Function:
4147 case OR_Deleted:
4148 // There was no suitable conversion, or we found a deleted
4149 // conversion; continue with other checks.
4150 return false;
4151 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004152
David Blaikie7530c032012-01-17 06:56:22 +00004153 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redl4680bf22010-06-30 18:13:39 +00004154}
4155
Douglas Gregorabe183d2010-04-13 16:31:36 +00004156/// \brief Compute an implicit conversion sequence for reference
4157/// initialization.
4158static ImplicitConversionSequence
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004159TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004160 SourceLocation DeclLoc,
4161 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00004162 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004163 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4164
4165 // Most paths end in a failed conversion.
4166 ImplicitConversionSequence ICS;
4167 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4168
4169 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4170 QualType T2 = Init->getType();
4171
4172 // If the initializer is the address of an overloaded function, try
4173 // to resolve the overloaded function. If all goes well, T2 is the
4174 // type of the resulting function.
4175 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4176 DeclAccessPair Found;
4177 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4178 false, Found))
4179 T2 = Fn->getType();
4180 }
4181
4182 // Compute some basic properties of the types and the initializer.
4183 bool isRValRef = DeclType->isRValueReferenceType();
4184 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00004185 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004186 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004187 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004188 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00004189 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00004190 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004191
Douglas Gregorabe183d2010-04-13 16:31:36 +00004192
Sebastian Redl4680bf22010-06-30 18:13:39 +00004193 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00004194 // A reference to type "cv1 T1" is initialized by an expression
4195 // of type "cv2 T2" as follows:
4196
Sebastian Redl4680bf22010-06-30 18:13:39 +00004197 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004198 if (!isRValRef) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004199 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4200 // reference-compatible with "cv2 T2," or
4201 //
4202 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4203 if (InitCategory.isLValue() &&
4204 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004205 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00004206 // When a parameter of reference type binds directly (8.5.3)
4207 // to an argument expression, the implicit conversion sequence
4208 // is the identity conversion, unless the argument expression
4209 // has a type that is a derived class of the parameter type,
4210 // in which case the implicit conversion sequence is a
4211 // derived-to-base Conversion (13.3.3.1).
4212 ICS.setStandard();
4213 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00004214 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4215 : ObjCConversion? ICK_Compatible_Conversion
4216 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004217 ICS.Standard.Third = ICK_Identity;
4218 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4219 ICS.Standard.setToType(0, T2);
4220 ICS.Standard.setToType(1, T1);
4221 ICS.Standard.setToType(2, T1);
4222 ICS.Standard.ReferenceBinding = true;
4223 ICS.Standard.DirectBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004224 ICS.Standard.IsLvalueReference = !isRValRef;
4225 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4226 ICS.Standard.BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004227 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004228 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004229 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004230
Sebastian Redl4680bf22010-06-30 18:13:39 +00004231 // Nothing more to do: the inaccessibility/ambiguity check for
4232 // derived-to-base conversions is suppressed when we're
4233 // computing the implicit conversion sequence (C++
4234 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00004235 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004236 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00004237
Sebastian Redl4680bf22010-06-30 18:13:39 +00004238 // -- has a class type (i.e., T2 is a class type), where T1 is
4239 // not reference-related to T2, and can be implicitly
4240 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4241 // is reference-compatible with "cv3 T3" 92) (this
4242 // conversion is selected by enumerating the applicable
4243 // conversion functions (13.3.1.6) and choosing the best
4244 // one through overload resolution (13.3)),
4245 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004246 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redl4680bf22010-06-30 18:13:39 +00004247 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00004248 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4249 Init, T2, /*AllowRvalues=*/false,
4250 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00004251 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004252 }
4253 }
4254
Sebastian Redl4680bf22010-06-30 18:13:39 +00004255 // -- Otherwise, the reference shall be an lvalue reference to a
4256 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004257 // shall be an rvalue reference.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004258 //
Douglas Gregor66821b52010-04-18 09:22:00 +00004259 // We actually handle one oddity of C++ [over.ics.ref] at this
4260 // point, which is that, due to p2 (which short-circuits reference
4261 // binding by only attempting a simple conversion for non-direct
4262 // bindings) and p3's strange wording, we allow a const volatile
4263 // reference to bind to an rvalue. Hence the check for the presence
4264 // of "const" rather than checking for "const" being the only
4265 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00004266 // This is also the point where rvalue references and lvalue inits no longer
4267 // go together.
Richard Smith8ab10aa2012-05-24 04:29:20 +00004268 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregorabe183d2010-04-13 16:31:36 +00004269 return ICS;
4270
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004271 // -- If the initializer expression
4272 //
4273 // -- is an xvalue, class prvalue, array prvalue or function
John McCallf85e1932011-06-15 23:02:42 +00004274 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004275 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4276 (InitCategory.isXValue() ||
4277 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4278 (InitCategory.isLValue() && T2->isFunctionType()))) {
4279 ICS.setStandard();
4280 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004281 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004282 : ObjCConversion? ICK_Compatible_Conversion
4283 : ICK_Identity;
4284 ICS.Standard.Third = ICK_Identity;
4285 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4286 ICS.Standard.setToType(0, T2);
4287 ICS.Standard.setToType(1, T1);
4288 ICS.Standard.setToType(2, T1);
4289 ICS.Standard.ReferenceBinding = true;
4290 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4291 // binding unless we're binding to a class prvalue.
4292 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4293 // allow the use of rvalue references in C++98/03 for the benefit of
4294 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004295 ICS.Standard.DirectBinding =
Richard Smith80ad52f2013-01-02 11:42:31 +00004296 S.getLangOpts().CPlusPlus11 ||
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004297 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregor440a4832011-01-26 14:52:12 +00004298 ICS.Standard.IsLvalueReference = !isRValRef;
4299 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004300 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004301 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004302 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004303 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004304 return ICS;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004305 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004306
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004307 // -- has a class type (i.e., T2 is a class type), where T1 is not
4308 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004309 // an xvalue, class prvalue, or function lvalue of type
4310 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004311 // "cv3 T3",
4312 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004313 // then the reference is bound to the value of the initializer
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004314 // expression in the first case and to the result of the conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004315 // in the second case (or, in either case, to an appropriate base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004316 // class subobject).
4317 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004318 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004319 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4320 Init, T2, /*AllowRvalues=*/true,
4321 AllowExplicit)) {
4322 // In the second case, if the reference is an rvalue reference
4323 // and the second standard conversion sequence of the
4324 // user-defined conversion sequence includes an lvalue-to-rvalue
4325 // conversion, the program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004326 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004327 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4328 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4329
Douglas Gregor68ed68b2011-01-21 16:36:05 +00004330 return ICS;
Rafael Espindolaaa5952c2011-01-22 15:32:35 +00004331 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004332
Douglas Gregorabe183d2010-04-13 16:31:36 +00004333 // -- Otherwise, a temporary of type "cv1 T1" is created and
4334 // initialized from the initializer expression using the
4335 // rules for a non-reference copy initialization (8.5). The
4336 // reference is then bound to the temporary. If T1 is
4337 // reference-related to T2, cv1 must be the same
4338 // cv-qualification as, or greater cv-qualification than,
4339 // cv2; otherwise, the program is ill-formed.
4340 if (RefRelationship == Sema::Ref_Related) {
4341 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4342 // we would be reference-compatible or reference-compatible with
4343 // added qualification. But that wasn't the case, so the reference
4344 // initialization fails.
John McCallf85e1932011-06-15 23:02:42 +00004345 //
4346 // Note that we only want to check address spaces and cvr-qualifiers here.
4347 // ObjC GC and lifetime qualifiers aren't important.
4348 Qualifiers T1Quals = T1.getQualifiers();
4349 Qualifiers T2Quals = T2.getQualifiers();
4350 T1Quals.removeObjCGCAttr();
4351 T1Quals.removeObjCLifetime();
4352 T2Quals.removeObjCGCAttr();
4353 T2Quals.removeObjCLifetime();
4354 if (!T1Quals.compatiblyIncludes(T2Quals))
4355 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004356 }
4357
4358 // If at least one of the types is a class type, the types are not
4359 // related, and we aren't allowed any user conversions, the
4360 // reference binding fails. This case is important for breaking
4361 // recursion, since TryImplicitConversion below will attempt to
4362 // create a temporary through the use of a copy constructor.
4363 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4364 (T1->isRecordType() || T2->isRecordType()))
4365 return ICS;
4366
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004367 // If T1 is reference-related to T2 and the reference is an rvalue
4368 // reference, the initializer expression shall not be an lvalue.
4369 if (RefRelationship >= Sema::Ref_Related &&
4370 isRValRef && Init->Classify(S.Context).isLValue())
4371 return ICS;
4372
Douglas Gregorabe183d2010-04-13 16:31:36 +00004373 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00004374 // When a parameter of reference type is not bound directly to
4375 // an argument expression, the conversion sequence is the one
4376 // required to convert the argument expression to the
4377 // underlying type of the reference according to
4378 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4379 // to copy-initializing a temporary of the underlying type with
4380 // the argument expression. Any difference in top-level
4381 // cv-qualification is subsumed by the initialization itself
4382 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00004383 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4384 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004385 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004386 /*CStyle=*/false,
Douglas Gregor1ce55092013-11-07 22:34:54 +00004387 /*AllowObjCWritebackConversion=*/false,
4388 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004389
4390 // Of course, that's still a reference binding.
4391 if (ICS.isStandard()) {
4392 ICS.Standard.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004393 ICS.Standard.IsLvalueReference = !isRValRef;
4394 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4395 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004396 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004397 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004398 } else if (ICS.isUserDefined()) {
Douglas Gregor203050c2011-10-04 23:59:32 +00004399 // Don't allow rvalue references to bind to lvalues.
4400 if (DeclType->isRValueReferenceType()) {
4401 if (const ReferenceType *RefType
4402 = ICS.UserDefined.ConversionFunction->getResultType()
4403 ->getAs<LValueReferenceType>()) {
4404 if (!RefType->getPointeeType()->isFunctionType()) {
4405 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4406 DeclType);
4407 return ICS;
4408 }
4409 }
4410 }
4411
Douglas Gregorabe183d2010-04-13 16:31:36 +00004412 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregorf20d2722011-08-15 13:59:46 +00004413 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4414 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4415 ICS.UserDefined.After.BindsToRvalue = true;
4416 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4417 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004418 }
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004419
Douglas Gregorabe183d2010-04-13 16:31:36 +00004420 return ICS;
4421}
4422
Sebastian Redl5405b812011-10-16 18:19:34 +00004423static ImplicitConversionSequence
4424TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4425 bool SuppressUserConversions,
4426 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004427 bool AllowObjCWritebackConversion,
4428 bool AllowExplicit = false);
Sebastian Redl5405b812011-10-16 18:19:34 +00004429
4430/// TryListConversion - Try to copy-initialize a value of type ToType from the
4431/// initializer list From.
4432static ImplicitConversionSequence
4433TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4434 bool SuppressUserConversions,
4435 bool InOverloadResolution,
4436 bool AllowObjCWritebackConversion) {
4437 // C++11 [over.ics.list]p1:
4438 // When an argument is an initializer list, it is not an expression and
4439 // special rules apply for converting it to a parameter type.
4440
4441 ImplicitConversionSequence Result;
4442 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4443
Sebastian Redlb832f6d2012-01-23 22:09:39 +00004444 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redlfe592282012-01-17 22:49:48 +00004445 // initialized from init lists.
Douglas Gregord10099e2012-05-04 16:32:21 +00004446 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redlfe592282012-01-17 22:49:48 +00004447 return Result;
4448
Sebastian Redl5405b812011-10-16 18:19:34 +00004449 // C++11 [over.ics.list]p2:
4450 // If the parameter type is std::initializer_list<X> or "array of X" and
4451 // all the elements can be implicitly converted to X, the implicit
4452 // conversion sequence is the worst conversion necessary to convert an
4453 // element of the list to X.
Sebastian Redladfb5352012-02-27 22:38:26 +00004454 bool toStdInitializerList = false;
Sebastian Redlfe592282012-01-17 22:49:48 +00004455 QualType X;
Sebastian Redl5405b812011-10-16 18:19:34 +00004456 if (ToType->isArrayType())
Richard Smith2801d9a2012-12-09 06:48:56 +00004457 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redlfe592282012-01-17 22:49:48 +00004458 else
Sebastian Redladfb5352012-02-27 22:38:26 +00004459 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redlfe592282012-01-17 22:49:48 +00004460 if (!X.isNull()) {
4461 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4462 Expr *Init = From->getInit(i);
4463 ImplicitConversionSequence ICS =
4464 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4465 InOverloadResolution,
4466 AllowObjCWritebackConversion);
4467 // If a single element isn't convertible, fail.
4468 if (ICS.isBad()) {
4469 Result = ICS;
4470 break;
4471 }
4472 // Otherwise, look for the worst conversion.
4473 if (Result.isBad() ||
4474 CompareImplicitConversionSequences(S, ICS, Result) ==
4475 ImplicitConversionSequence::Worse)
4476 Result = ICS;
4477 }
Douglas Gregor5b4bf132012-04-04 23:09:20 +00004478
4479 // For an empty list, we won't have computed any conversion sequence.
4480 // Introduce the identity conversion sequence.
4481 if (From->getNumInits() == 0) {
4482 Result.setStandard();
4483 Result.Standard.setAsIdentityConversion();
4484 Result.Standard.setFromType(ToType);
4485 Result.Standard.setAllToTypes(ToType);
4486 }
4487
Sebastian Redladfb5352012-02-27 22:38:26 +00004488 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redl5405b812011-10-16 18:19:34 +00004489 return Result;
Sebastian Redlfe592282012-01-17 22:49:48 +00004490 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004491
4492 // C++11 [over.ics.list]p3:
4493 // Otherwise, if the parameter is a non-aggregate class X and overload
4494 // resolution chooses a single best constructor [...] the implicit
4495 // conversion sequence is a user-defined conversion sequence. If multiple
4496 // constructors are viable but none is better than the others, the
4497 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004498 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4499 // This function can deal with initializer lists.
Richard Smith798186a2013-09-06 22:30:28 +00004500 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4501 /*AllowExplicit=*/false,
4502 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor1ce55092013-11-07 22:34:54 +00004503 AllowObjCWritebackConversion,
4504 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004505 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004506
4507 // C++11 [over.ics.list]p4:
4508 // Otherwise, if the parameter has an aggregate type which can be
4509 // initialized from the initializer list [...] the implicit conversion
4510 // sequence is a user-defined conversion sequence.
Sebastian Redl5405b812011-10-16 18:19:34 +00004511 if (ToType->isAggregateType()) {
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004512 // Type is an aggregate, argument is an init list. At this point it comes
4513 // down to checking whether the initialization works.
4514 // FIXME: Find out whether this parameter is consumed or not.
4515 InitializedEntity Entity =
4516 InitializedEntity::InitializeParameter(S.Context, ToType,
4517 /*Consumed=*/false);
4518 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4519 Result.setUserDefined();
4520 Result.UserDefined.Before.setAsIdentityConversion();
4521 // Initializer lists don't have a type.
4522 Result.UserDefined.Before.setFromType(QualType());
4523 Result.UserDefined.Before.setAllToTypes(QualType());
4524
4525 Result.UserDefined.After.setAsIdentityConversion();
4526 Result.UserDefined.After.setFromType(ToType);
4527 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramer83db10e2012-02-02 19:35:29 +00004528 Result.UserDefined.ConversionFunction = 0;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004529 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004530 return Result;
4531 }
4532
4533 // C++11 [over.ics.list]p5:
4534 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004535 if (ToType->isReferenceType()) {
4536 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4537 // mention initializer lists in any way. So we go by what list-
4538 // initialization would do and try to extrapolate from that.
4539
4540 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4541
4542 // If the initializer list has a single element that is reference-related
4543 // to the parameter type, we initialize the reference from that.
4544 if (From->getNumInits() == 1) {
4545 Expr *Init = From->getInit(0);
4546
4547 QualType T2 = Init->getType();
4548
4549 // If the initializer is the address of an overloaded function, try
4550 // to resolve the overloaded function. If all goes well, T2 is the
4551 // type of the resulting function.
4552 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4553 DeclAccessPair Found;
4554 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4555 Init, ToType, false, Found))
4556 T2 = Fn->getType();
4557 }
4558
4559 // Compute some basic properties of the types and the initializer.
4560 bool dummy1 = false;
4561 bool dummy2 = false;
4562 bool dummy3 = false;
4563 Sema::ReferenceCompareResult RefRelationship
4564 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4565 dummy2, dummy3);
4566
Richard Smith3082be22013-09-06 01:22:42 +00004567 if (RefRelationship >= Sema::Ref_Related) {
Richard Smith798186a2013-09-06 22:30:28 +00004568 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4569 SuppressUserConversions,
4570 /*AllowExplicit=*/false);
Richard Smith3082be22013-09-06 01:22:42 +00004571 }
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004572 }
4573
4574 // Otherwise, we bind the reference to a temporary created from the
4575 // initializer list.
4576 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4577 InOverloadResolution,
4578 AllowObjCWritebackConversion);
4579 if (Result.isFailure())
4580 return Result;
4581 assert(!Result.isEllipsis() &&
4582 "Sub-initialization cannot result in ellipsis conversion.");
4583
4584 // Can we even bind to a temporary?
4585 if (ToType->isRValueReferenceType() ||
4586 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4587 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4588 Result.UserDefined.After;
4589 SCS.ReferenceBinding = true;
4590 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4591 SCS.BindsToRvalue = true;
4592 SCS.BindsToFunctionLvalue = false;
4593 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4594 SCS.ObjCLifetimeConversionBinding = false;
4595 } else
4596 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4597 From, ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004598 return Result;
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004599 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004600
4601 // C++11 [over.ics.list]p6:
4602 // Otherwise, if the parameter type is not a class:
4603 if (!ToType->isRecordType()) {
4604 // - if the initializer list has one element, the implicit conversion
4605 // sequence is the one required to convert the element to the
4606 // parameter type.
Sebastian Redl5405b812011-10-16 18:19:34 +00004607 unsigned NumInits = From->getNumInits();
4608 if (NumInits == 1)
4609 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4610 SuppressUserConversions,
4611 InOverloadResolution,
4612 AllowObjCWritebackConversion);
4613 // - if the initializer list has no elements, the implicit conversion
4614 // sequence is the identity conversion.
4615 else if (NumInits == 0) {
4616 Result.setStandard();
4617 Result.Standard.setAsIdentityConversion();
John McCalle14ba2c2012-04-04 02:40:27 +00004618 Result.Standard.setFromType(ToType);
4619 Result.Standard.setAllToTypes(ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004620 }
4621 return Result;
4622 }
4623
4624 // C++11 [over.ics.list]p7:
4625 // In all cases other than those enumerated above, no conversion is possible
4626 return Result;
4627}
4628
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004629/// TryCopyInitialization - Try to copy-initialize a value of type
4630/// ToType from the expression From. Return the implicit conversion
4631/// sequence required to pass this argument, which may be a bad
4632/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00004633/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00004634/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00004635static ImplicitConversionSequence
4636TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004637 bool SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004638 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004639 bool AllowObjCWritebackConversion,
4640 bool AllowExplicit) {
Sebastian Redl5405b812011-10-16 18:19:34 +00004641 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4642 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4643 InOverloadResolution,AllowObjCWritebackConversion);
4644
Douglas Gregorabe183d2010-04-13 16:31:36 +00004645 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00004646 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004647 /*FIXME:*/From->getLocStart(),
4648 SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00004649 AllowExplicit);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004650
John McCall120d63c2010-08-24 20:38:10 +00004651 return TryImplicitConversion(S, From, ToType,
4652 SuppressUserConversions,
4653 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004654 InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00004655 /*CStyle=*/false,
Douglas Gregor1ce55092013-11-07 22:34:54 +00004656 AllowObjCWritebackConversion,
4657 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004658}
4659
Anna Zaksf3546ee2011-07-28 19:46:48 +00004660static bool TryCopyInitialization(const CanQualType FromQTy,
4661 const CanQualType ToQTy,
4662 Sema &S,
4663 SourceLocation Loc,
4664 ExprValueKind FromVK) {
4665 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4666 ImplicitConversionSequence ICS =
4667 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4668
4669 return !ICS.isBad();
4670}
4671
Douglas Gregor96176b32008-11-18 23:14:02 +00004672/// TryObjectArgumentInitialization - Try to initialize the object
4673/// parameter of the given member function (@c Method) from the
4674/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00004675static ImplicitConversionSequence
Richard Smith98bfbf52013-01-26 02:07:32 +00004676TryObjectArgumentInitialization(Sema &S, QualType FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004677 Expr::Classification FromClassification,
John McCall120d63c2010-08-24 20:38:10 +00004678 CXXMethodDecl *Method,
4679 CXXRecordDecl *ActingContext) {
4680 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00004681 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4682 // const volatile object.
4683 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4684 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00004685 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00004686
4687 // Set up the conversion sequence as a "bad" conversion, to allow us
4688 // to exit early.
4689 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00004690
4691 // We need to have an object of class type.
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004692 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004693 FromType = PT->getPointeeType();
4694
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004695 // When we had a pointer, it's implicitly dereferenced, so we
4696 // better have an lvalue.
4697 assert(FromClassification.isLValue());
4698 }
4699
Anders Carlssona552f7c2009-05-01 18:34:30 +00004700 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00004701
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004702 // C++0x [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004703 // For non-static member functions, the type of the implicit object
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004704 // parameter is
4705 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004706 // - "lvalue reference to cv X" for functions declared without a
4707 // ref-qualifier or with the & ref-qualifier
4708 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004709 // ref-qualifier
4710 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004711 // where X is the class of which the function is a member and cv is the
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004712 // cv-qualification on the member function declaration.
4713 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004714 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004715 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00004716 // (C++ [over.match.funcs]p5). We perform a simplified version of
4717 // reference binding here, that allows class rvalues to bind to
4718 // non-constant references.
4719
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004720 // First check the qualifiers.
John McCall120d63c2010-08-24 20:38:10 +00004721 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004722 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregora4923eb2009-11-16 21:35:15 +00004723 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00004724 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00004725 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith98bfbf52013-01-26 02:07:32 +00004726 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004727 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004728 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004729
4730 // Check that we have either the same type or a derived type. It
4731 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00004732 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00004733 ImplicitConversionKind SecondKind;
4734 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4735 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00004736 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00004737 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00004738 else {
John McCallb1bdc622010-02-25 01:37:24 +00004739 ICS.setBad(BadConversionSequence::unrelated_class,
4740 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004741 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004742 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004743
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004744 // Check the ref-qualifier.
4745 switch (Method->getRefQualifier()) {
4746 case RQ_None:
4747 // Do nothing; we don't care about lvalueness or rvalueness.
4748 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004749
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004750 case RQ_LValue:
4751 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4752 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004753 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004754 ImplicitParamType);
4755 return ICS;
4756 }
4757 break;
4758
4759 case RQ_RValue:
4760 if (!FromClassification.isRValue()) {
4761 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004762 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004763 ImplicitParamType);
4764 return ICS;
4765 }
4766 break;
4767 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004768
Douglas Gregor96176b32008-11-18 23:14:02 +00004769 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004770 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00004771 ICS.Standard.setAsIdentityConversion();
4772 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00004773 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004774 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004775 ICS.Standard.ReferenceBinding = true;
4776 ICS.Standard.DirectBinding = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004777 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregor440a4832011-01-26 14:52:12 +00004778 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004779 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4780 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4781 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor96176b32008-11-18 23:14:02 +00004782 return ICS;
4783}
4784
4785/// PerformObjectArgumentInitialization - Perform initialization of
4786/// the implicit object parameter for the given Method with the given
4787/// expression.
John Wiegley429bb272011-04-08 18:41:53 +00004788ExprResult
4789Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004790 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00004791 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00004792 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004793 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00004794 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00004795 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004796
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004797 Expr::Classification FromClassification;
Ted Kremenek6217b802009-07-29 21:53:49 +00004798 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004799 FromRecordType = PT->getPointeeType();
4800 DestType = Method->getThisType(Context);
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004801 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004802 } else {
4803 FromRecordType = From->getType();
4804 DestType = ImplicitParamRecordType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004805 FromClassification = From->Classify(Context);
Anders Carlssona552f7c2009-05-01 18:34:30 +00004806 }
4807
John McCall701c89e2009-12-03 04:06:58 +00004808 // Note that we always use the true parent context when performing
4809 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004810 ImplicitConversionSequence ICS
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004811 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4812 Method, Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004813 if (ICS.isBad()) {
4814 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4815 Qualifiers FromQs = FromRecordType.getQualifiers();
4816 Qualifiers ToQs = DestType.getQualifiers();
4817 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4818 if (CVR) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004819 Diag(From->getLocStart(),
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004820 diag::err_member_function_call_bad_cvr)
4821 << Method->getDeclName() << FromRecordType << (CVR - 1)
4822 << From->getSourceRange();
4823 Diag(Method->getLocation(), diag::note_previous_decl)
4824 << Method->getDeclName();
John Wiegley429bb272011-04-08 18:41:53 +00004825 return ExprError();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004826 }
4827 }
4828
Daniel Dunbar96a00142012-03-09 18:35:03 +00004829 return Diag(From->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004830 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00004831 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004832 }
Mike Stump1eb44332009-09-09 15:08:12 +00004833
John Wiegley429bb272011-04-08 18:41:53 +00004834 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4835 ExprResult FromRes =
4836 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4837 if (FromRes.isInvalid())
4838 return ExprError();
4839 From = FromRes.take();
4840 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004841
Douglas Gregor5fccd362010-03-03 23:55:11 +00004842 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley429bb272011-04-08 18:41:53 +00004843 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smithacdfa4d2011-11-10 23:32:36 +00004844 From->getValueKind()).take();
John Wiegley429bb272011-04-08 18:41:53 +00004845 return Owned(From);
Douglas Gregor96176b32008-11-18 23:14:02 +00004846}
4847
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004848/// TryContextuallyConvertToBool - Attempt to contextually convert the
4849/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00004850static ImplicitConversionSequence
4851TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall120d63c2010-08-24 20:38:10 +00004852 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004853 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00004854 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004855 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004856 /*CStyle=*/false,
Douglas Gregor1ce55092013-11-07 22:34:54 +00004857 /*AllowObjCWritebackConversion=*/false,
4858 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004859}
4860
4861/// PerformContextuallyConvertToBool - Perform a contextual conversion
4862/// of the expression From to bool (C++0x [conv]p3).
John Wiegley429bb272011-04-08 18:41:53 +00004863ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004864 if (checkPlaceholderForOverload(*this, From))
4865 return ExprError();
4866
John McCall120d63c2010-08-24 20:38:10 +00004867 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00004868 if (!ICS.isBad())
4869 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004870
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00004871 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004872 return Diag(From->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +00004873 diag::err_typecheck_bool_condition)
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00004874 << From->getType() << From->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004875 return ExprError();
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004876}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004877
Richard Smith8ef7b202012-01-18 23:55:52 +00004878/// Check that the specified conversion is permitted in a converted constant
4879/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4880/// is acceptable.
4881static bool CheckConvertedConstantConversions(Sema &S,
4882 StandardConversionSequence &SCS) {
4883 // Since we know that the target type is an integral or unscoped enumeration
4884 // type, most conversion kinds are impossible. All possible First and Third
4885 // conversions are fine.
4886 switch (SCS.Second) {
4887 case ICK_Identity:
4888 case ICK_Integral_Promotion:
4889 case ICK_Integral_Conversion:
Guy Benyei6959acd2013-02-07 16:05:33 +00004890 case ICK_Zero_Event_Conversion:
Richard Smith8ef7b202012-01-18 23:55:52 +00004891 return true;
4892
4893 case ICK_Boolean_Conversion:
Richard Smith2bcb9842012-09-13 22:00:12 +00004894 // Conversion from an integral or unscoped enumeration type to bool is
4895 // classified as ICK_Boolean_Conversion, but it's also an integral
4896 // conversion, so it's permitted in a converted constant expression.
4897 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4898 SCS.getToType(2)->isBooleanType();
4899
Richard Smith8ef7b202012-01-18 23:55:52 +00004900 case ICK_Floating_Integral:
4901 case ICK_Complex_Real:
4902 return false;
4903
4904 case ICK_Lvalue_To_Rvalue:
4905 case ICK_Array_To_Pointer:
4906 case ICK_Function_To_Pointer:
4907 case ICK_NoReturn_Adjustment:
4908 case ICK_Qualification:
4909 case ICK_Compatible_Conversion:
4910 case ICK_Vector_Conversion:
4911 case ICK_Vector_Splat:
4912 case ICK_Derived_To_Base:
4913 case ICK_Pointer_Conversion:
4914 case ICK_Pointer_Member:
4915 case ICK_Block_Pointer_Conversion:
4916 case ICK_Writeback_Conversion:
4917 case ICK_Floating_Promotion:
4918 case ICK_Complex_Promotion:
4919 case ICK_Complex_Conversion:
4920 case ICK_Floating_Conversion:
4921 case ICK_TransparentUnionConversion:
4922 llvm_unreachable("unexpected second conversion kind");
4923
4924 case ICK_Num_Conversion_Kinds:
4925 break;
4926 }
4927
4928 llvm_unreachable("unknown conversion kind");
4929}
4930
4931/// CheckConvertedConstantExpression - Check that the expression From is a
4932/// converted constant expression of type T, perform the conversion and produce
4933/// the converted expression, per C++11 [expr.const]p3.
4934ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4935 llvm::APSInt &Value,
4936 CCEKind CCE) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004937 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
Richard Smith8ef7b202012-01-18 23:55:52 +00004938 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4939
4940 if (checkPlaceholderForOverload(*this, From))
4941 return ExprError();
4942
4943 // C++11 [expr.const]p3 with proposed wording fixes:
4944 // A converted constant expression of type T is a core constant expression,
4945 // implicitly converted to a prvalue of type T, where the converted
4946 // expression is a literal constant expression and the implicit conversion
4947 // sequence contains only user-defined conversions, lvalue-to-rvalue
4948 // conversions, integral promotions, and integral conversions other than
4949 // narrowing conversions.
4950 ImplicitConversionSequence ICS =
4951 TryImplicitConversion(From, T,
4952 /*SuppressUserConversions=*/false,
4953 /*AllowExplicit=*/false,
4954 /*InOverloadResolution=*/false,
4955 /*CStyle=*/false,
4956 /*AllowObjcWritebackConversion=*/false);
4957 StandardConversionSequence *SCS = 0;
4958 switch (ICS.getKind()) {
4959 case ImplicitConversionSequence::StandardConversion:
4960 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004961 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004962 diag::err_typecheck_converted_constant_expression_disallowed)
4963 << From->getType() << From->getSourceRange() << T;
4964 SCS = &ICS.Standard;
4965 break;
4966 case ImplicitConversionSequence::UserDefinedConversion:
4967 // We are converting from class type to an integral or enumeration type, so
4968 // the Before sequence must be trivial.
4969 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004970 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004971 diag::err_typecheck_converted_constant_expression_disallowed)
4972 << From->getType() << From->getSourceRange() << T;
4973 SCS = &ICS.UserDefined.After;
4974 break;
4975 case ImplicitConversionSequence::AmbiguousConversion:
4976 case ImplicitConversionSequence::BadConversion:
4977 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004978 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004979 diag::err_typecheck_converted_constant_expression)
4980 << From->getType() << From->getSourceRange() << T;
4981 return ExprError();
4982
4983 case ImplicitConversionSequence::EllipsisConversion:
4984 llvm_unreachable("ellipsis conversion in converted constant expression");
4985 }
4986
4987 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4988 if (Result.isInvalid())
4989 return Result;
4990
4991 // Check for a narrowing implicit conversion.
4992 APValue PreNarrowingValue;
Richard Smithf6028062012-03-23 23:55:39 +00004993 QualType PreNarrowingType;
Richard Smithf6028062012-03-23 23:55:39 +00004994 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4995 PreNarrowingType)) {
Richard Smith8ef7b202012-01-18 23:55:52 +00004996 case NK_Variable_Narrowing:
4997 // Implicit conversion to a narrower type, and the value is not a constant
4998 // expression. We'll diagnose this in a moment.
4999 case NK_Not_Narrowing:
5000 break;
5001
5002 case NK_Constant_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00005003 Diag(From->getLocStart(),
5004 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
5005 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00005006 << CCE << /*Constant*/1
Richard Smithf6028062012-03-23 23:55:39 +00005007 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smith8ef7b202012-01-18 23:55:52 +00005008 break;
5009
5010 case NK_Type_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00005011 Diag(From->getLocStart(),
5012 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
5013 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00005014 << CCE << /*Constant*/0 << From->getType() << T;
5015 break;
5016 }
5017
5018 // Check the expression is a constant expression.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005019 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith8ef7b202012-01-18 23:55:52 +00005020 Expr::EvalResult Eval;
5021 Eval.Diag = &Notes;
5022
Douglas Gregor484f6fa2013-04-08 23:24:07 +00005023 if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) {
Richard Smith8ef7b202012-01-18 23:55:52 +00005024 // The expression can't be folded, so we can't keep it at this position in
5025 // the AST.
5026 Result = ExprError();
Richard Smithf72fccf2012-01-30 22:27:01 +00005027 } else {
Richard Smith8ef7b202012-01-18 23:55:52 +00005028 Value = Eval.Val.getInt();
Richard Smithf72fccf2012-01-30 22:27:01 +00005029
5030 if (Notes.empty()) {
5031 // It's a constant expression.
5032 return Result;
5033 }
Richard Smith8ef7b202012-01-18 23:55:52 +00005034 }
5035
5036 // It's not a constant expression. Produce an appropriate diagnostic.
5037 if (Notes.size() == 1 &&
5038 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5039 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5040 else {
Daniel Dunbar96a00142012-03-09 18:35:03 +00005041 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smith8ef7b202012-01-18 23:55:52 +00005042 << CCE << From->getSourceRange();
5043 for (unsigned I = 0; I < Notes.size(); ++I)
5044 Diag(Notes[I].first, Notes[I].second);
5045 }
Richard Smithf72fccf2012-01-30 22:27:01 +00005046 return Result;
Richard Smith8ef7b202012-01-18 23:55:52 +00005047}
5048
John McCall0bcc9bc2011-09-09 06:11:02 +00005049/// dropPointerConversions - If the given standard conversion sequence
5050/// involves any pointer conversions, remove them. This may change
5051/// the result type of the conversion sequence.
5052static void dropPointerConversion(StandardConversionSequence &SCS) {
5053 if (SCS.Second == ICK_Pointer_Conversion) {
5054 SCS.Second = ICK_Identity;
5055 SCS.Third = ICK_Identity;
5056 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5057 }
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005058}
John McCall120d63c2010-08-24 20:38:10 +00005059
John McCall0bcc9bc2011-09-09 06:11:02 +00005060/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5061/// convert the expression From to an Objective-C pointer type.
5062static ImplicitConversionSequence
5063TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5064 // Do an implicit conversion to 'id'.
5065 QualType Ty = S.Context.getObjCIdType();
5066 ImplicitConversionSequence ICS
5067 = TryImplicitConversion(S, From, Ty,
5068 // FIXME: Are these flags correct?
5069 /*SuppressUserConversions=*/false,
5070 /*AllowExplicit=*/true,
5071 /*InOverloadResolution=*/false,
5072 /*CStyle=*/false,
Douglas Gregor1ce55092013-11-07 22:34:54 +00005073 /*AllowObjCWritebackConversion=*/false,
5074 /*AllowObjCConversionOnExplicit=*/true);
John McCall0bcc9bc2011-09-09 06:11:02 +00005075
5076 // Strip off any final conversions to 'id'.
5077 switch (ICS.getKind()) {
5078 case ImplicitConversionSequence::BadConversion:
5079 case ImplicitConversionSequence::AmbiguousConversion:
5080 case ImplicitConversionSequence::EllipsisConversion:
5081 break;
5082
5083 case ImplicitConversionSequence::UserDefinedConversion:
5084 dropPointerConversion(ICS.UserDefined.After);
5085 break;
5086
5087 case ImplicitConversionSequence::StandardConversion:
5088 dropPointerConversion(ICS.Standard);
5089 break;
5090 }
5091
5092 return ICS;
5093}
5094
5095/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5096/// conversion of the expression From to an Objective-C pointer type.
5097ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00005098 if (checkPlaceholderForOverload(*this, From))
5099 return ExprError();
5100
John McCallc12c5bb2010-05-15 11:32:37 +00005101 QualType Ty = Context.getObjCIdType();
John McCall0bcc9bc2011-09-09 06:11:02 +00005102 ImplicitConversionSequence ICS =
5103 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005104 if (!ICS.isBad())
5105 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley429bb272011-04-08 18:41:53 +00005106 return ExprError();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005107}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005108
Richard Smithf39aec12012-02-04 07:07:42 +00005109/// Determine whether the provided type is an integral type, or an enumeration
5110/// type of a permitted flavor.
Richard Smith097e0a22013-05-21 19:05:48 +00005111bool Sema::ICEConvertDiagnoser::match(QualType T) {
5112 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5113 : T->isIntegralOrUnscopedEnumerationType();
Richard Smithf39aec12012-02-04 07:07:42 +00005114}
5115
Larisse Voufo50b60b32013-06-10 06:50:24 +00005116static ExprResult
5117diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5118 Sema::ContextualImplicitConverter &Converter,
5119 QualType T, UnresolvedSetImpl &ViableConversions) {
5120
5121 if (Converter.Suppress)
5122 return ExprError();
5123
5124 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5125 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5126 CXXConversionDecl *Conv =
5127 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5128 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5129 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5130 }
5131 return SemaRef.Owned(From);
5132}
5133
5134static bool
5135diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5136 Sema::ContextualImplicitConverter &Converter,
5137 QualType T, bool HadMultipleCandidates,
5138 UnresolvedSetImpl &ExplicitConversions) {
5139 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5140 DeclAccessPair Found = ExplicitConversions[0];
5141 CXXConversionDecl *Conversion =
5142 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5143
5144 // The user probably meant to invoke the given explicit
5145 // conversion; use it.
5146 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5147 std::string TypeStr;
5148 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5149
5150 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5151 << FixItHint::CreateInsertion(From->getLocStart(),
5152 "static_cast<" + TypeStr + ">(")
5153 << FixItHint::CreateInsertion(
5154 SemaRef.PP.getLocForEndOfToken(From->getLocEnd()), ")");
5155 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5156
5157 // If we aren't in a SFINAE context, build a call to the
5158 // explicit conversion function.
5159 if (SemaRef.isSFINAEContext())
5160 return true;
5161
5162 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5163 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5164 HadMultipleCandidates);
5165 if (Result.isInvalid())
5166 return true;
5167 // Record usage of conversion in an implicit cast.
5168 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5169 CK_UserDefinedConversion, Result.get(), 0,
5170 Result.get()->getValueKind());
5171 }
5172 return false;
5173}
5174
5175static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5176 Sema::ContextualImplicitConverter &Converter,
5177 QualType T, bool HadMultipleCandidates,
5178 DeclAccessPair &Found) {
5179 CXXConversionDecl *Conversion =
5180 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5181 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5182
5183 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5184 if (!Converter.SuppressConversion) {
5185 if (SemaRef.isSFINAEContext())
5186 return true;
5187
5188 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5189 << From->getSourceRange();
5190 }
5191
5192 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5193 HadMultipleCandidates);
5194 if (Result.isInvalid())
5195 return true;
5196 // Record usage of conversion in an implicit cast.
5197 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5198 CK_UserDefinedConversion, Result.get(), 0,
5199 Result.get()->getValueKind());
5200 return false;
5201}
5202
5203static ExprResult finishContextualImplicitConversion(
5204 Sema &SemaRef, SourceLocation Loc, Expr *From,
5205 Sema::ContextualImplicitConverter &Converter) {
5206 if (!Converter.match(From->getType()) && !Converter.Suppress)
5207 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5208 << From->getSourceRange();
5209
5210 return SemaRef.DefaultLvalueConversion(From);
5211}
5212
5213static void
5214collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5215 UnresolvedSetImpl &ViableConversions,
5216 OverloadCandidateSet &CandidateSet) {
5217 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5218 DeclAccessPair FoundDecl = ViableConversions[I];
5219 NamedDecl *D = FoundDecl.getDecl();
5220 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5221 if (isa<UsingShadowDecl>(D))
5222 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5223
5224 CXXConversionDecl *Conv;
5225 FunctionTemplateDecl *ConvTemplate;
5226 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5227 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5228 else
5229 Conv = cast<CXXConversionDecl>(D);
5230
5231 if (ConvTemplate)
5232 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor1ce55092013-11-07 22:34:54 +00005233 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5234 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo50b60b32013-06-10 06:50:24 +00005235 else
5236 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor1ce55092013-11-07 22:34:54 +00005237 ToType, CandidateSet,
5238 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo50b60b32013-06-10 06:50:24 +00005239 }
5240}
5241
Richard Smith097e0a22013-05-21 19:05:48 +00005242/// \brief Attempt to convert the given expression to a type which is accepted
5243/// by the given converter.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005244///
Richard Smith097e0a22013-05-21 19:05:48 +00005245/// This routine will attempt to convert an expression of class type to a
5246/// type accepted by the specified converter. In C++11 and before, the class
5247/// must have a single non-explicit conversion function converting to a matching
5248/// type. In C++1y, there can be multiple such conversion functions, but only
5249/// one target type.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005250///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005251/// \param Loc The source location of the construct that requires the
5252/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005253///
James Dennett40ae6662012-06-22 08:52:37 +00005254/// \param From The expression we're converting from.
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005255///
Richard Smith097e0a22013-05-21 19:05:48 +00005256/// \param Converter Used to control and diagnose the conversion process.
Richard Smithf39aec12012-02-04 07:07:42 +00005257///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005258/// \returns The expression, converted to an integral or enumeration type if
5259/// successful.
Richard Smith097e0a22013-05-21 19:05:48 +00005260ExprResult Sema::PerformContextualImplicitConversion(
5261 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005262 // We can't perform any more checking for type-dependent expressions.
5263 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00005264 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005265
Eli Friedmanceccab92012-01-26 00:26:18 +00005266 // Process placeholders immediately.
5267 if (From->hasPlaceholderType()) {
5268 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo50b60b32013-06-10 06:50:24 +00005269 if (result.isInvalid())
5270 return result;
Eli Friedmanceccab92012-01-26 00:26:18 +00005271 From = result.take();
5272 }
5273
Richard Smith097e0a22013-05-21 19:05:48 +00005274 // If the expression already has a matching type, we're golden.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005275 QualType T = From->getType();
Richard Smith097e0a22013-05-21 19:05:48 +00005276 if (Converter.match(T))
Eli Friedmanceccab92012-01-26 00:26:18 +00005277 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005278
5279 // FIXME: Check for missing '()' if T is a function type?
5280
Richard Smith097e0a22013-05-21 19:05:48 +00005281 // We can only perform contextual implicit conversions on objects of class
5282 // type.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005283 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikie4e4d0842012-03-11 07:00:24 +00005284 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smith097e0a22013-05-21 19:05:48 +00005285 if (!Converter.Suppress)
5286 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00005287 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005288 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005289
Douglas Gregorc30614b2010-06-29 23:17:37 +00005290 // We must have a complete class type.
Douglas Gregorf502d8e2012-05-04 16:48:41 +00005291 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smith097e0a22013-05-21 19:05:48 +00005292 ContextualImplicitConverter &Converter;
Douglas Gregorab41fe92012-05-04 22:38:52 +00005293 Expr *From;
Richard Smith097e0a22013-05-21 19:05:48 +00005294
5295 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5296 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5297
Douglas Gregord10099e2012-05-04 16:32:21 +00005298 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Richard Smith097e0a22013-05-21 19:05:48 +00005299 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregord10099e2012-05-04 16:32:21 +00005300 }
Richard Smith097e0a22013-05-21 19:05:48 +00005301 } IncompleteDiagnoser(Converter, From);
Douglas Gregord10099e2012-05-04 16:32:21 +00005302
5303 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCall9ae2f072010-08-23 23:25:46 +00005304 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005305
Douglas Gregorc30614b2010-06-29 23:17:37 +00005306 // Look for a conversion to an integral or enumeration type.
Larisse Voufo50b60b32013-06-10 06:50:24 +00005307 UnresolvedSet<4>
5308 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005309 UnresolvedSet<4> ExplicitConversions;
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00005310 std::pair<CXXRecordDecl::conversion_iterator,
Larisse Voufo50b60b32013-06-10 06:50:24 +00005311 CXXRecordDecl::conversion_iterator> Conversions =
5312 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005313
Larisse Voufo50b60b32013-06-10 06:50:24 +00005314 bool HadMultipleCandidates =
5315 (std::distance(Conversions.first, Conversions.second) > 1);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005316
Larisse Voufo50b60b32013-06-10 06:50:24 +00005317 // To check that there is only one target type, in C++1y:
5318 QualType ToType;
5319 bool HasUniqueTargetType = true;
5320
5321 // Collect explicit or viable (potentially in C++1y) conversions.
5322 for (CXXRecordDecl::conversion_iterator I = Conversions.first,
5323 E = Conversions.second;
5324 I != E; ++I) {
5325 NamedDecl *D = (*I)->getUnderlyingDecl();
5326 CXXConversionDecl *Conversion;
5327 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5328 if (ConvTemplate) {
5329 if (getLangOpts().CPlusPlus1y)
5330 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5331 else
5332 continue; // C++11 does not consider conversion operator templates(?).
5333 } else
5334 Conversion = cast<CXXConversionDecl>(D);
5335
5336 assert((!ConvTemplate || getLangOpts().CPlusPlus1y) &&
5337 "Conversion operator templates are considered potentially "
5338 "viable in C++1y");
5339
5340 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5341 if (Converter.match(CurToType) || ConvTemplate) {
5342
5343 if (Conversion->isExplicit()) {
5344 // FIXME: For C++1y, do we need this restriction?
5345 // cf. diagnoseNoViableConversion()
5346 if (!ConvTemplate)
Douglas Gregorc30614b2010-06-29 23:17:37 +00005347 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo50b60b32013-06-10 06:50:24 +00005348 } else {
5349 if (!ConvTemplate && getLangOpts().CPlusPlus1y) {
5350 if (ToType.isNull())
5351 ToType = CurToType.getUnqualifiedType();
5352 else if (HasUniqueTargetType &&
5353 (CurToType.getUnqualifiedType() != ToType))
5354 HasUniqueTargetType = false;
5355 }
5356 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005357 }
Richard Smithf39aec12012-02-04 07:07:42 +00005358 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005359 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005360
Larisse Voufo50b60b32013-06-10 06:50:24 +00005361 if (getLangOpts().CPlusPlus1y) {
5362 // C++1y [conv]p6:
5363 // ... An expression e of class type E appearing in such a context
5364 // is said to be contextually implicitly converted to a specified
5365 // type T and is well-formed if and only if e can be implicitly
5366 // converted to a type T that is determined as follows: E is searched
Larisse Voufo7acc5a62013-06-10 08:25:58 +00005367 // for conversion functions whose return type is cv T or reference to
5368 // cv T such that T is allowed by the context. There shall be
Larisse Voufo50b60b32013-06-10 06:50:24 +00005369 // exactly one such T.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005370
Larisse Voufo50b60b32013-06-10 06:50:24 +00005371 // If no unique T is found:
5372 if (ToType.isNull()) {
5373 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5374 HadMultipleCandidates,
5375 ExplicitConversions))
Douglas Gregorc30614b2010-06-29 23:17:37 +00005376 return ExprError();
Larisse Voufo50b60b32013-06-10 06:50:24 +00005377 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005378 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005379
Larisse Voufo50b60b32013-06-10 06:50:24 +00005380 // If more than one unique Ts are found:
5381 if (!HasUniqueTargetType)
5382 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5383 ViableConversions);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005384
Larisse Voufo50b60b32013-06-10 06:50:24 +00005385 // If one unique T is found:
5386 // First, build a candidate set from the previously recorded
5387 // potentially viable conversions.
5388 OverloadCandidateSet CandidateSet(Loc);
5389 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5390 CandidateSet);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005391
Larisse Voufo50b60b32013-06-10 06:50:24 +00005392 // Then, perform overload resolution over the candidate set.
5393 OverloadCandidateSet::iterator Best;
5394 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5395 case OR_Success: {
5396 // Apply this conversion.
5397 DeclAccessPair Found =
5398 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5399 if (recordConversion(*this, Loc, From, Converter, T,
5400 HadMultipleCandidates, Found))
5401 return ExprError();
5402 break;
5403 }
5404 case OR_Ambiguous:
5405 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5406 ViableConversions);
5407 case OR_No_Viable_Function:
5408 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5409 HadMultipleCandidates,
5410 ExplicitConversions))
5411 return ExprError();
5412 // fall through 'OR_Deleted' case.
5413 case OR_Deleted:
5414 // We'll complain below about a non-integral condition type.
5415 break;
5416 }
5417 } else {
5418 switch (ViableConversions.size()) {
5419 case 0: {
5420 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5421 HadMultipleCandidates,
5422 ExplicitConversions))
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005423 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005424
Larisse Voufo50b60b32013-06-10 06:50:24 +00005425 // We'll complain below about a non-integral condition type.
5426 break;
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005427 }
Larisse Voufo50b60b32013-06-10 06:50:24 +00005428 case 1: {
5429 // Apply this conversion.
5430 DeclAccessPair Found = ViableConversions[0];
5431 if (recordConversion(*this, Loc, From, Converter, T,
5432 HadMultipleCandidates, Found))
5433 return ExprError();
5434 break;
5435 }
5436 default:
5437 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5438 ViableConversions);
5439 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005440 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005441
Larisse Voufo50b60b32013-06-10 06:50:24 +00005442 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005443}
5444
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005445/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00005446/// candidate functions, using the given function call arguments. If
5447/// @p SuppressUserConversions, then don't allow user-defined
5448/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005449///
James Dennett699c9042012-06-15 07:13:21 +00005450/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005451/// based on an incomplete set of function arguments. This feature is used by
5452/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00005453void
5454Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00005455 DeclAccessPair FoundDecl,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005456 ArrayRef<Expr *> Args,
Douglas Gregor225c41e2008-11-03 19:09:14 +00005457 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00005458 bool SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00005459 bool PartialOverloading,
5460 bool AllowExplicit) {
Mike Stump1eb44332009-09-09 15:08:12 +00005461 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005462 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005463 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00005464 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi00995302011-01-27 07:09:49 +00005465 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00005466
Douglas Gregor88a35142008-12-22 05:46:06 +00005467 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005468 if (!isa<CXXConstructorDecl>(Method)) {
5469 // If we get here, it's because we're calling a member function
5470 // that is named without a member access expression (e.g.,
5471 // "this->f") that was either written explicitly or created
5472 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00005473 // function, e.g., X::f(). We use an empty type for the implied
5474 // object argument (C++ [over.call.func]p3), and the acting context
5475 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00005476 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005477 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005478 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005479 return;
5480 }
5481 // We treat a constructor like a non-member function, since its object
5482 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00005483 }
5484
Douglas Gregorfd476482009-11-13 23:59:09 +00005485 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00005486 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00005487
Richard Smith743cbb92013-11-04 01:48:18 +00005488 // C++11 [class.copy]p11: [DR1402]
5489 // A defaulted move constructor that is defined as deleted is ignored by
5490 // overload resolution.
5491 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5492 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5493 Constructor->isMoveConstructor())
5494 return;
5495
Douglas Gregor7edfb692009-11-23 12:27:39 +00005496 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005497 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005498
Richard Smith743cbb92013-11-04 01:48:18 +00005499 if (Constructor) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00005500 // C++ [class.copy]p3:
5501 // A member function template is never instantiated to perform the copy
5502 // of a class object to an object of its class type.
5503 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charles13a140c2012-02-25 11:00:22 +00005504 if (Args.size() == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00005505 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00005506 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5507 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00005508 return;
5509 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005510
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005511 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005512 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCall9aa472c2010-03-19 07:35:19 +00005513 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005514 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00005515 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005516 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005517 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005518 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005519
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005520 unsigned NumArgsInProto = Proto->getNumArgs();
5521
5522 // (C++ 13.3.2p2): A candidate function having fewer than m
5523 // parameters is viable only if it has an ellipsis in its parameter
5524 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005525 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor5bd1a112009-09-23 14:56:09 +00005526 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005527 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005528 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005529 return;
5530 }
5531
5532 // (C++ 13.3.2p2): A candidate function having more than m parameters
5533 // is viable only if the (m+1)st parameter has a default argument
5534 // (8.3.6). For the purposes of overload resolution, the
5535 // parameter list is truncated on the right, so that there are
5536 // exactly m parameters.
5537 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005538 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005539 // Not enough arguments.
5540 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005541 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005542 return;
5543 }
5544
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005545 // (CUDA B.1): Check for invalid calls between targets.
David Blaikie4e4d0842012-03-11 07:00:24 +00005546 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005547 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5548 if (CheckCUDATarget(Caller, Function)) {
5549 Candidate.Viable = false;
5550 Candidate.FailureKind = ovl_fail_bad_target;
5551 return;
5552 }
5553
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005554 // Determine the implicit conversion sequences for each of the
5555 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005556 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005557 if (ArgIdx < NumArgsInProto) {
5558 // (C++ 13.3.2p3): for F to be a viable function, there shall
5559 // exist for each argument an implicit conversion sequence
5560 // (13.3.3.1) that converts that argument to the corresponding
5561 // parameter of F.
5562 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005563 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005564 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005565 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005566 /*InOverloadResolution=*/true,
5567 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005568 getLangOpts().ObjCAutoRefCount,
Douglas Gregored878af2012-02-24 23:56:31 +00005569 AllowExplicit);
John McCall1d318332010-01-12 00:44:57 +00005570 if (Candidate.Conversions[ArgIdx].isBad()) {
5571 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005572 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00005573 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00005574 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005575 } else {
5576 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5577 // argument for which there is no corresponding parameter is
5578 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005579 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005580 }
5581 }
5582}
5583
Douglas Gregor063daf62009-03-13 18:40:31 +00005584/// \brief Add all of the function declarations in the given function set to
Nick Lewycky199e3702013-09-22 10:06:01 +00005585/// the overload candidate set.
John McCall6e266892010-01-26 03:27:55 +00005586void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005587 ArrayRef<Expr *> Args,
Douglas Gregor063daf62009-03-13 18:40:31 +00005588 OverloadCandidateSet& CandidateSet,
Richard Smith36f5cfe2012-03-09 08:00:36 +00005589 bool SuppressUserConversions,
5590 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall6e266892010-01-26 03:27:55 +00005591 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00005592 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5593 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005594 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005595 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005596 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005597 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005598 Args.slice(1), CandidateSet,
5599 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005600 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00005601 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00005602 SuppressUserConversions);
5603 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005604 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00005605 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5606 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005607 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005608 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005609 ExplicitTemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005610 Args[0]->getType(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005611 Args[0]->Classify(Context), Args.slice(1),
5612 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005613 else
John McCall9aa472c2010-03-19 07:35:19 +00005614 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005615 ExplicitTemplateArgs, Args,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005616 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005617 }
Douglas Gregor364e0212009-06-27 21:05:07 +00005618 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005619}
5620
John McCall314be4e2009-11-17 07:50:12 +00005621/// AddMethodCandidate - Adds a named decl (which is some kind of
5622/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00005623void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005624 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005625 Expr::Classification ObjectClassification,
Rafael Espindola548107e2013-04-29 19:29:25 +00005626 ArrayRef<Expr *> Args,
John McCall314be4e2009-11-17 07:50:12 +00005627 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005628 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00005629 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00005630 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00005631
5632 if (isa<UsingShadowDecl>(Decl))
5633 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005634
John McCall314be4e2009-11-17 07:50:12 +00005635 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5636 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5637 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00005638 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5639 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005640 ObjectType, ObjectClassification,
Rafael Espindola548107e2013-04-29 19:29:25 +00005641 Args, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005642 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005643 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005644 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005645 ObjectType, ObjectClassification,
Rafael Espindola548107e2013-04-29 19:29:25 +00005646 Args,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005647 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005648 }
5649}
5650
Douglas Gregor96176b32008-11-18 23:14:02 +00005651/// AddMethodCandidate - Adds the given C++ member function to the set
5652/// of candidate functions, using the given function call arguments
5653/// and the object argument (@c Object). For example, in a call
5654/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5655/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5656/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00005657/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00005658void
John McCall9aa472c2010-03-19 07:35:19 +00005659Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00005660 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005661 Expr::Classification ObjectClassification,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005662 ArrayRef<Expr *> Args,
Douglas Gregor96176b32008-11-18 23:14:02 +00005663 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005664 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00005665 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005666 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00005667 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005668 assert(!isa<CXXConstructorDecl>(Method) &&
5669 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00005670
Douglas Gregor3f396022009-09-28 04:47:19 +00005671 if (!CandidateSet.isNewCandidate(Method))
5672 return;
5673
Richard Smith743cbb92013-11-04 01:48:18 +00005674 // C++11 [class.copy]p23: [DR1402]
5675 // A defaulted move assignment operator that is defined as deleted is
5676 // ignored by overload resolution.
5677 if (Method->isDefaulted() && Method->isDeleted() &&
5678 Method->isMoveAssignmentOperator())
5679 return;
5680
Douglas Gregor7edfb692009-11-23 12:27:39 +00005681 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005682 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005683
Douglas Gregor96176b32008-11-18 23:14:02 +00005684 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005685 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005686 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00005687 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005688 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005689 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005690 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor96176b32008-11-18 23:14:02 +00005691
5692 unsigned NumArgsInProto = Proto->getNumArgs();
5693
5694 // (C++ 13.3.2p2): A candidate function having fewer than m
5695 // parameters is viable only if it has an ellipsis in its parameter
5696 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005697 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005698 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005699 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005700 return;
5701 }
5702
5703 // (C++ 13.3.2p2): A candidate function having more than m parameters
5704 // is viable only if the (m+1)st parameter has a default argument
5705 // (8.3.6). For the purposes of overload resolution, the
5706 // parameter list is truncated on the right, so that there are
5707 // exactly m parameters.
5708 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005709 if (Args.size() < MinRequiredArgs) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005710 // Not enough arguments.
5711 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005712 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005713 return;
5714 }
5715
5716 Candidate.Viable = true;
Douglas Gregor96176b32008-11-18 23:14:02 +00005717
John McCall701c89e2009-12-03 04:06:58 +00005718 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00005719 // The implicit object argument is ignored.
5720 Candidate.IgnoreObjectArgument = true;
5721 else {
5722 // Determine the implicit conversion sequence for the object
5723 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00005724 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005725 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5726 Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005727 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00005728 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005729 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00005730 return;
5731 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005732 }
5733
5734 // Determine the implicit conversion sequences for each of the
5735 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005736 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005737 if (ArgIdx < NumArgsInProto) {
5738 // (C++ 13.3.2p3): for F to be a viable function, there shall
5739 // exist for each argument an implicit conversion sequence
5740 // (13.3.3.1) that converts that argument to the corresponding
5741 // parameter of F.
5742 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005743 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005744 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005745 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005746 /*InOverloadResolution=*/true,
5747 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005748 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005749 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005750 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005751 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00005752 break;
5753 }
5754 } else {
5755 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5756 // argument for which there is no corresponding parameter is
5757 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005758 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00005759 }
5760 }
5761}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005762
Douglas Gregor6b906862009-08-21 00:16:32 +00005763/// \brief Add a C++ member function template as a candidate to the candidate
5764/// set, using template argument deduction to produce an appropriate member
5765/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005766void
Douglas Gregor6b906862009-08-21 00:16:32 +00005767Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00005768 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005769 CXXRecordDecl *ActingContext,
Douglas Gregor67714232011-03-03 02:41:12 +00005770 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00005771 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005772 Expr::Classification ObjectClassification,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005773 ArrayRef<Expr *> Args,
Douglas Gregor6b906862009-08-21 00:16:32 +00005774 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005775 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005776 if (!CandidateSet.isNewCandidate(MethodTmpl))
5777 return;
5778
Douglas Gregor6b906862009-08-21 00:16:32 +00005779 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005780 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00005781 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005782 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00005783 // candidate functions in the usual way.113) A given name can refer to one
5784 // or more function templates and also to a set of overloaded non-template
5785 // functions. In such a case, the candidate functions generated from each
5786 // function template are combined with the set of non-template candidate
5787 // functions.
Craig Topper93e45992012-09-19 02:26:47 +00005788 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00005789 FunctionDecl *Specialization = 0;
5790 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005791 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5792 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005793 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005794 Candidate.FoundDecl = FoundDecl;
5795 Candidate.Function = MethodTmpl->getTemplatedDecl();
5796 Candidate.Viable = false;
5797 Candidate.FailureKind = ovl_fail_bad_deduction;
5798 Candidate.IsSurrogate = false;
5799 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005800 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005801 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005802 Info);
5803 return;
5804 }
Mike Stump1eb44332009-09-09 15:08:12 +00005805
Douglas Gregor6b906862009-08-21 00:16:32 +00005806 // Add the function template specialization produced by template argument
5807 // deduction as a candidate.
5808 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00005809 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00005810 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00005811 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005812 ActingContext, ObjectType, ObjectClassification, Args,
5813 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00005814}
5815
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005816/// \brief Add a C++ function template specialization as a candidate
5817/// in the candidate set, using template argument deduction to produce
5818/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005819void
Douglas Gregore53060f2009-06-25 22:08:12 +00005820Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005821 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00005822 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005823 ArrayRef<Expr *> Args,
Douglas Gregore53060f2009-06-25 22:08:12 +00005824 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005825 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005826 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5827 return;
5828
Douglas Gregore53060f2009-06-25 22:08:12 +00005829 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005830 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00005831 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005832 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00005833 // candidate functions in the usual way.113) A given name can refer to one
5834 // or more function templates and also to a set of overloaded non-template
5835 // functions. In such a case, the candidate functions generated from each
5836 // function template are combined with the set of non-template candidate
5837 // functions.
Craig Topper93e45992012-09-19 02:26:47 +00005838 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00005839 FunctionDecl *Specialization = 0;
5840 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005841 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5842 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005843 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCall9aa472c2010-03-19 07:35:19 +00005844 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00005845 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5846 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005847 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00005848 Candidate.IsSurrogate = false;
5849 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005850 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005851 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005852 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00005853 return;
5854 }
Mike Stump1eb44332009-09-09 15:08:12 +00005855
Douglas Gregore53060f2009-06-25 22:08:12 +00005856 // Add the function template specialization produced by template argument
5857 // deduction as a candidate.
5858 assert(Specialization && "Missing function template specialization?");
Ahmed Charles13a140c2012-02-25 11:00:22 +00005859 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005860 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00005861}
Mike Stump1eb44332009-09-09 15:08:12 +00005862
Douglas Gregor1ce55092013-11-07 22:34:54 +00005863/// Determine whether this is an allowable conversion from the result
5864/// of an explicit conversion operator to the expected type, per C++
5865/// [over.match.conv]p1 and [over.match.ref]p1.
5866///
5867/// \param ConvType The return type of the conversion function.
5868///
5869/// \param ToType The type we are converting to.
5870///
5871/// \param AllowObjCPointerConversion Allow a conversion from one
5872/// Objective-C pointer to another.
5873///
5874/// \returns true if the conversion is allowable, false otherwise.
5875static bool isAllowableExplicitConversion(Sema &S,
5876 QualType ConvType, QualType ToType,
5877 bool AllowObjCPointerConversion) {
5878 QualType ToNonRefType = ToType.getNonReferenceType();
5879
5880 // Easy case: the types are the same.
5881 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
5882 return true;
5883
5884 // Allow qualification conversions.
5885 bool ObjCLifetimeConversion;
5886 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
5887 ObjCLifetimeConversion))
5888 return true;
5889
5890 // If we're not allowed to consider Objective-C pointer conversions,
5891 // we're done.
5892 if (!AllowObjCPointerConversion)
5893 return false;
5894
5895 // Is this an Objective-C pointer conversion?
5896 bool IncompatibleObjC = false;
5897 QualType ConvertedType;
5898 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
5899 IncompatibleObjC);
5900}
5901
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005902/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00005903/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005904/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00005905/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005906/// (which may or may not be the same type as the type that the
5907/// conversion function produces).
5908void
5909Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005910 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005911 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005912 Expr *From, QualType ToType,
Douglas Gregor1ce55092013-11-07 22:34:54 +00005913 OverloadCandidateSet& CandidateSet,
5914 bool AllowObjCConversionOnExplicit) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005915 assert(!Conversion->getDescribedFunctionTemplate() &&
5916 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005917 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00005918 if (!CandidateSet.isNewCandidate(Conversion))
5919 return;
5920
Richard Smith60e141e2013-05-04 07:00:32 +00005921 // If the conversion function has an undeduced return type, trigger its
5922 // deduction now.
5923 if (getLangOpts().CPlusPlus1y && ConvType->isUndeducedType()) {
5924 if (DeduceReturnType(Conversion, From->getExprLoc()))
5925 return;
5926 ConvType = Conversion->getConversionType().getNonReferenceType();
5927 }
5928
Richard Smithb390e492013-09-21 21:55:46 +00005929 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
5930 // operator is only a candidate if its return type is the target type or
5931 // can be converted to the target type with a qualification conversion.
Douglas Gregor1ce55092013-11-07 22:34:54 +00005932 if (Conversion->isExplicit() &&
5933 !isAllowableExplicitConversion(*this, ConvType, ToType,
5934 AllowObjCConversionOnExplicit))
Richard Smithb390e492013-09-21 21:55:46 +00005935 return;
5936
Douglas Gregor7edfb692009-11-23 12:27:39 +00005937 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005938 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005939
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005940 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005941 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCall9aa472c2010-03-19 07:35:19 +00005942 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005943 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005944 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005945 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005946 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005947 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00005948 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005949 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005950 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005951
Douglas Gregorbca39322010-08-19 15:37:02 +00005952 // C++ [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005953 // For conversion functions, the function is considered to be a member of
5954 // the class of the implicit implied object argument for the purpose of
Douglas Gregorbca39322010-08-19 15:37:02 +00005955 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005956 //
5957 // Determine the implicit conversion sequence for the implicit
5958 // object parameter.
5959 QualType ImplicitParamType = From->getType();
5960 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5961 ImplicitParamType = FromPtrType->getPointeeType();
5962 CXXRecordDecl *ConversionContext
5963 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005964
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005965 Candidate.Conversions[0]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005966 = TryObjectArgumentInitialization(*this, From->getType(),
5967 From->Classify(Context),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005968 Conversion, ConversionContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005969
John McCall1d318332010-01-12 00:44:57 +00005970 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005971 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005972 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005973 return;
5974 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005975
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005976 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005977 // derived to base as such conversions are given Conversion Rank. They only
5978 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5979 QualType FromCanon
5980 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5981 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5982 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5983 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005984 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005985 return;
5986 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005987
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005988 // To determine what the conversion from the result of calling the
5989 // conversion function to the type we're eventually trying to
5990 // convert to (ToType), we need to synthesize a call to the
5991 // conversion function and attempt copy initialization from it. This
5992 // makes sure that we get the right semantics with respect to
5993 // lvalues/rvalues and the type. Fortunately, we can allocate this
5994 // call on the stack and we don't need its arguments to be
5995 // well-formed.
John McCallf4b88a42012-03-10 09:33:50 +00005996 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005997 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00005998 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5999 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00006000 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00006001 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00006002
Richard Smith87c1f1f2011-07-13 22:53:21 +00006003 QualType ConversionType = Conversion->getConversionType();
6004 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor7d14d382010-11-13 19:36:57 +00006005 Candidate.Viable = false;
6006 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6007 return;
6008 }
6009
Richard Smith87c1f1f2011-07-13 22:53:21 +00006010 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCallf89e55a2010-11-18 06:31:45 +00006011
Mike Stump1eb44332009-09-09 15:08:12 +00006012 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00006013 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6014 // allocator).
Richard Smith87c1f1f2011-07-13 22:53:21 +00006015 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00006016 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00006017 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00006018 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00006019 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00006020 /*SuppressUserConversions=*/true,
John McCallf85e1932011-06-15 23:02:42 +00006021 /*InOverloadResolution=*/false,
6022 /*AllowObjCWritebackConversion=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00006023
John McCall1d318332010-01-12 00:44:57 +00006024 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00006025 case ImplicitConversionSequence::StandardConversion:
6026 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006027
Douglas Gregorc520c842010-04-12 23:42:09 +00006028 // C++ [over.ics.user]p3:
6029 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006030 // conversion function template, the second standard conversion sequence
Douglas Gregorc520c842010-04-12 23:42:09 +00006031 // shall have exact match rank.
6032 if (Conversion->getPrimaryTemplate() &&
6033 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6034 Candidate.Viable = false;
6035 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6036 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006037
Douglas Gregor2ad746a2011-01-21 05:18:22 +00006038 // C++0x [dcl.init.ref]p5:
6039 // In the second case, if the reference is an rvalue reference and
6040 // the second standard conversion sequence of the user-defined
6041 // conversion sequence includes an lvalue-to-rvalue conversion, the
6042 // program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006043 if (ToType->isRValueReferenceType() &&
Douglas Gregor2ad746a2011-01-21 05:18:22 +00006044 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6045 Candidate.Viable = false;
6046 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6047 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00006048 break;
6049
6050 case ImplicitConversionSequence::BadConversion:
6051 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00006052 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00006053 break;
6054
6055 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00006056 llvm_unreachable(
Douglas Gregorf1991ea2008-11-07 22:36:19 +00006057 "Can only end up with a standard conversion sequence or failure");
6058 }
6059}
6060
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006061/// \brief Adds a conversion function template specialization
6062/// candidate to the overload set, using template argument deduction
6063/// to deduce the template arguments of the conversion function
6064/// template from the type that we are converting to (C++
6065/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00006066void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006067Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00006068 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00006069 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006070 Expr *From, QualType ToType,
Douglas Gregor1ce55092013-11-07 22:34:54 +00006071 OverloadCandidateSet &CandidateSet,
6072 bool AllowObjCConversionOnExplicit) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006073 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6074 "Only conversion function templates permitted here");
6075
Douglas Gregor3f396022009-09-28 04:47:19 +00006076 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6077 return;
6078
Craig Topper93e45992012-09-19 02:26:47 +00006079 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006080 CXXConversionDecl *Specialization = 0;
6081 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00006082 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006083 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00006084 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00006085 Candidate.FoundDecl = FoundDecl;
6086 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6087 Candidate.Viable = false;
6088 Candidate.FailureKind = ovl_fail_bad_deduction;
6089 Candidate.IsSurrogate = false;
6090 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00006091 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006092 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00006093 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006094 return;
6095 }
Mike Stump1eb44332009-09-09 15:08:12 +00006096
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006097 // Add the conversion function template specialization produced by
6098 // template argument deduction as a candidate.
6099 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00006100 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor1ce55092013-11-07 22:34:54 +00006101 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006102}
6103
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006104/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6105/// converts the given @c Object to a function pointer via the
6106/// conversion function @c Conversion, and then attempts to call it
6107/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6108/// the type of function that we'll eventually be calling.
6109void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00006110 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00006111 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00006112 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006113 Expr *Object,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006114 ArrayRef<Expr *> Args,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006115 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00006116 if (!CandidateSet.isNewCandidate(Conversion))
6117 return;
6118
Douglas Gregor7edfb692009-11-23 12:27:39 +00006119 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00006120 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00006121
Ahmed Charles13a140c2012-02-25 11:00:22 +00006122 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00006123 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006124 Candidate.Function = 0;
6125 Candidate.Surrogate = Conversion;
6126 Candidate.Viable = true;
6127 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00006128 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00006129 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006130
6131 // Determine the implicit conversion sequence for the implicit
6132 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00006133 ImplicitConversionSequence ObjectInit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006134 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006135 Object->Classify(Context),
6136 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00006137 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006138 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006139 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00006140 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006141 return;
6142 }
6143
6144 // The first conversion is actually a user-defined conversion whose
6145 // first conversion is ObjectInit's standard conversion (which is
6146 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00006147 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006148 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00006149 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00006150 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006151 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00006152 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00006153 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006154 = Candidate.Conversions[0].UserDefined.Before;
6155 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6156
Mike Stump1eb44332009-09-09 15:08:12 +00006157 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006158 unsigned NumArgsInProto = Proto->getNumArgs();
6159
6160 // (C++ 13.3.2p2): A candidate function having fewer than m
6161 // parameters is viable only if it has an ellipsis in its parameter
6162 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00006163 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006164 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006165 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006166 return;
6167 }
6168
6169 // Function types don't have any default arguments, so just check if
6170 // we have enough arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00006171 if (Args.size() < NumArgsInProto) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006172 // Not enough arguments.
6173 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006174 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006175 return;
6176 }
6177
6178 // Determine the implicit conversion sequences for each of the
6179 // arguments.
Richard Smith958ba642013-05-05 15:51:06 +00006180 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006181 if (ArgIdx < NumArgsInProto) {
6182 // (C++ 13.3.2p3): for F to be a viable function, there shall
6183 // exist for each argument an implicit conversion sequence
6184 // (13.3.3.1) that converts that argument to the corresponding
6185 // parameter of F.
6186 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00006187 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006188 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00006189 /*SuppressUserConversions=*/false,
John McCallf85e1932011-06-15 23:02:42 +00006190 /*InOverloadResolution=*/false,
6191 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00006192 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00006193 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006194 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006195 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006196 break;
6197 }
6198 } else {
6199 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6200 // argument for which there is no corresponding parameter is
6201 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00006202 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006203 }
6204 }
6205}
6206
Douglas Gregor063daf62009-03-13 18:40:31 +00006207/// \brief Add overload candidates for overloaded operators that are
6208/// member functions.
6209///
6210/// Add the overloaded operator candidates that are member functions
6211/// for the operator Op that was used in an operator expression such
6212/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6213/// CandidateSet will store the added overload candidates. (C++
6214/// [over.match.oper]).
6215void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6216 SourceLocation OpLoc,
Richard Smith958ba642013-05-05 15:51:06 +00006217 ArrayRef<Expr *> Args,
Douglas Gregor063daf62009-03-13 18:40:31 +00006218 OverloadCandidateSet& CandidateSet,
6219 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00006220 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6221
6222 // C++ [over.match.oper]p3:
6223 // For a unary operator @ with an operand of a type whose
6224 // cv-unqualified version is T1, and for a binary operator @ with
6225 // a left operand of a type whose cv-unqualified version is T1 and
6226 // a right operand of a type whose cv-unqualified version is T2,
6227 // three sets of candidate functions, designated member
6228 // candidates, non-member candidates and built-in candidates, are
6229 // constructed as follows:
6230 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00006231
Richard Smithe410be92013-04-20 12:41:22 +00006232 // -- If T1 is a complete class type or a class currently being
6233 // defined, the set of member candidates is the result of the
6234 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6235 // the set of member candidates is empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00006236 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smithe410be92013-04-20 12:41:22 +00006237 // Complete the type if it can be completed.
6238 RequireCompleteType(OpLoc, T1, 0);
6239 // If the type is neither complete nor being defined, bail out now.
6240 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor8a5ae242009-08-27 23:35:55 +00006241 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006242
John McCalla24dc2e2009-11-17 02:14:36 +00006243 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6244 LookupQualifiedName(Operators, T1Rec->getDecl());
6245 Operators.suppressDiagnostics();
6246
Mike Stump1eb44332009-09-09 15:08:12 +00006247 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00006248 OperEnd = Operators.end();
6249 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00006250 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00006251 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola548107e2013-04-29 19:29:25 +00006252 Args[0]->Classify(Context),
Richard Smith958ba642013-05-05 15:51:06 +00006253 Args.slice(1),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006254 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00006255 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00006256 }
Douglas Gregor96176b32008-11-18 23:14:02 +00006257}
6258
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006259/// AddBuiltinCandidate - Add a candidate for a built-in
6260/// operator. ResultTy and ParamTys are the result and parameter types
6261/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006262/// arguments being passed to the candidate. IsAssignmentOperator
6263/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006264/// operator. NumContextualBoolArguments is the number of arguments
6265/// (at the beginning of the argument list) that will be contextually
6266/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00006267void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smith958ba642013-05-05 15:51:06 +00006268 ArrayRef<Expr *> Args,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006269 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006270 bool IsAssignmentOperator,
6271 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00006272 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00006273 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00006274
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006275 // Add this candidate
Richard Smith958ba642013-05-05 15:51:06 +00006276 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCall9aa472c2010-03-19 07:35:19 +00006277 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006278 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00006279 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00006280 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006281 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smith958ba642013-05-05 15:51:06 +00006282 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006283 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6284
6285 // Determine the implicit conversion sequences for each of the
6286 // arguments.
6287 Candidate.Viable = true;
Richard Smith958ba642013-05-05 15:51:06 +00006288 Candidate.ExplicitCallArguments = Args.size();
6289 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006290 // C++ [over.match.oper]p4:
6291 // For the built-in assignment operators, conversions of the
6292 // left operand are restricted as follows:
6293 // -- no temporaries are introduced to hold the left operand, and
6294 // -- no user-defined conversions are applied to the left
6295 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00006296 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006297 //
6298 // We block these conversions by turning off user-defined
6299 // conversions, since that is the only way that initialization of
6300 // a reference to a non-class type can occur from something that
6301 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006302 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00006303 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006304 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00006305 Candidate.Conversions[ArgIdx]
6306 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006307 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00006308 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006309 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00006310 ArgIdx == 0 && IsAssignmentOperator,
John McCallf85e1932011-06-15 23:02:42 +00006311 /*InOverloadResolution=*/false,
6312 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00006313 getLangOpts().ObjCAutoRefCount);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006314 }
John McCall1d318332010-01-12 00:44:57 +00006315 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006316 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006317 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00006318 break;
6319 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006320 }
6321}
6322
Craig Topperfe09f3f2013-07-01 06:29:40 +00006323namespace {
6324
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006325/// BuiltinCandidateTypeSet - A set of types that will be used for the
6326/// candidate operator functions for built-in operators (C++
6327/// [over.built]). The types are separated into pointer types and
6328/// enumeration types.
6329class BuiltinCandidateTypeSet {
6330 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006331 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006332
6333 /// PointerTypes - The set of pointer types that will be used in the
6334 /// built-in candidates.
6335 TypeSet PointerTypes;
6336
Sebastian Redl78eb8742009-04-19 21:53:20 +00006337 /// MemberPointerTypes - The set of member pointer types that will be
6338 /// used in the built-in candidates.
6339 TypeSet MemberPointerTypes;
6340
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006341 /// EnumerationTypes - The set of enumeration types that will be
6342 /// used in the built-in candidates.
6343 TypeSet EnumerationTypes;
6344
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006345 /// \brief The set of vector types that will be used in the built-in
Douglas Gregor26bcf672010-05-19 03:21:00 +00006346 /// candidates.
6347 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00006348
6349 /// \brief A flag indicating non-record types are viable candidates
6350 bool HasNonRecordTypes;
6351
6352 /// \brief A flag indicating whether either arithmetic or enumeration types
6353 /// were present in the candidate set.
6354 bool HasArithmeticOrEnumeralTypes;
6355
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006356 /// \brief A flag indicating whether the nullptr type was present in the
6357 /// candidate set.
6358 bool HasNullPtrType;
6359
Douglas Gregor5842ba92009-08-24 15:23:48 +00006360 /// Sema - The semantic analysis instance where we are building the
6361 /// candidate type set.
6362 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00006363
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006364 /// Context - The AST context in which we will build the type sets.
6365 ASTContext &Context;
6366
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006367 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6368 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00006369 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006370
6371public:
6372 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006373 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006374
Mike Stump1eb44332009-09-09 15:08:12 +00006375 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00006376 : HasNonRecordTypes(false),
6377 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006378 HasNullPtrType(false),
Chandler Carruth6a577462010-12-13 01:44:01 +00006379 SemaRef(SemaRef),
6380 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006381
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006382 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006383 SourceLocation Loc,
6384 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006385 bool AllowExplicitConversions,
6386 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006387
6388 /// pointer_begin - First pointer type found;
6389 iterator pointer_begin() { return PointerTypes.begin(); }
6390
Sebastian Redl78eb8742009-04-19 21:53:20 +00006391 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006392 iterator pointer_end() { return PointerTypes.end(); }
6393
Sebastian Redl78eb8742009-04-19 21:53:20 +00006394 /// member_pointer_begin - First member pointer type found;
6395 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6396
6397 /// member_pointer_end - Past the last member pointer type found;
6398 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6399
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006400 /// enumeration_begin - First enumeration type found;
6401 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6402
Sebastian Redl78eb8742009-04-19 21:53:20 +00006403 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006404 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006405
Douglas Gregor26bcf672010-05-19 03:21:00 +00006406 iterator vector_begin() { return VectorTypes.begin(); }
6407 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00006408
6409 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6410 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006411 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006412};
6413
Craig Topperfe09f3f2013-07-01 06:29:40 +00006414} // end anonymous namespace
6415
Sebastian Redl78eb8742009-04-19 21:53:20 +00006416/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006417/// the set of pointer types along with any more-qualified variants of
6418/// that type. For example, if @p Ty is "int const *", this routine
6419/// will add "int const *", "int const volatile *", "int const
6420/// restrict *", and "int const volatile restrict *" to the set of
6421/// pointer types. Returns true if the add of @p Ty itself succeeded,
6422/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006423///
6424/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006425bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00006426BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6427 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00006428
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006429 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006430 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006431 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006432
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006433 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00006434 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006435 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006436 if (!PointerTy) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006437 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6438 PointeeTy = PTy->getPointeeType();
6439 buildObjCPtr = true;
6440 } else {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006441 PointeeTy = PointerTy->getPointeeType();
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006442 }
6443
Sebastian Redla9efada2009-11-18 20:39:26 +00006444 // Don't add qualified variants of arrays. For one, they're not allowed
6445 // (the qualifier would sink to the element type), and for another, the
6446 // only overload situation where it matters is subscript or pointer +- int,
6447 // and those shouldn't have qualifier variants anyway.
6448 if (PointeeTy->isArrayType())
6449 return true;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006450
John McCall0953e762009-09-24 19:53:00 +00006451 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006452 bool hasVolatile = VisibleQuals.hasVolatile();
6453 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006454
John McCall0953e762009-09-24 19:53:00 +00006455 // Iterate through all strict supersets of BaseCVR.
6456 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6457 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006458 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006459 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006460
6461 // Skip over restrict if no restrict found anywhere in the types, or if
6462 // the type cannot be restrict-qualified.
6463 if ((CVR & Qualifiers::Restrict) &&
6464 (!hasRestrict ||
6465 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6466 continue;
6467
6468 // Build qualified pointee type.
John McCall0953e762009-09-24 19:53:00 +00006469 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006470
6471 // Build qualified pointer type.
6472 QualType QPointerTy;
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006473 if (!buildObjCPtr)
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006474 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006475 else
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006476 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6477
6478 // Insert qualified pointer type.
6479 PointerTypes.insert(QPointerTy);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006480 }
6481
6482 return true;
6483}
6484
Sebastian Redl78eb8742009-04-19 21:53:20 +00006485/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6486/// to the set of pointer types along with any more-qualified variants of
6487/// that type. For example, if @p Ty is "int const *", this routine
6488/// will add "int const *", "int const volatile *", "int const
6489/// restrict *", and "int const volatile restrict *" to the set of
6490/// pointer types. Returns true if the add of @p Ty itself succeeded,
6491/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006492///
6493/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006494bool
6495BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6496 QualType Ty) {
6497 // Insert this type.
6498 if (!MemberPointerTypes.insert(Ty))
6499 return false;
6500
John McCall0953e762009-09-24 19:53:00 +00006501 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6502 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00006503
John McCall0953e762009-09-24 19:53:00 +00006504 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00006505 // Don't add qualified variants of arrays. For one, they're not allowed
6506 // (the qualifier would sink to the element type), and for another, the
6507 // only overload situation where it matters is subscript or pointer +- int,
6508 // and those shouldn't have qualifier variants anyway.
6509 if (PointeeTy->isArrayType())
6510 return true;
John McCall0953e762009-09-24 19:53:00 +00006511 const Type *ClassTy = PointerTy->getClass();
6512
6513 // Iterate through all strict supersets of the pointee type's CVR
6514 // qualifiers.
6515 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6516 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6517 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006518
John McCall0953e762009-09-24 19:53:00 +00006519 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006520 MemberPointerTypes.insert(
6521 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00006522 }
6523
6524 return true;
6525}
6526
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006527/// AddTypesConvertedFrom - Add each of the types to which the type @p
6528/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00006529/// primarily interested in pointer types and enumeration types. We also
6530/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006531/// AllowUserConversions is true if we should look at the conversion
6532/// functions of a class type, and AllowExplicitConversions if we
6533/// should also include the explicit conversion functions of a class
6534/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00006535void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006536BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006537 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006538 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006539 bool AllowExplicitConversions,
6540 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006541 // Only deal with canonical types.
6542 Ty = Context.getCanonicalType(Ty);
6543
6544 // Look through reference types; they aren't part of the type of an
6545 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00006546 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006547 Ty = RefTy->getPointeeType();
6548
John McCall3b657512011-01-19 10:06:00 +00006549 // If we're dealing with an array type, decay to the pointer.
6550 if (Ty->isArrayType())
6551 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6552
6553 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006554 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006555
Chandler Carruth6a577462010-12-13 01:44:01 +00006556 // Flag if we ever add a non-record type.
6557 const RecordType *TyRec = Ty->getAs<RecordType>();
6558 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6559
Chandler Carruth6a577462010-12-13 01:44:01 +00006560 // Flag if we encounter an arithmetic type.
6561 HasArithmeticOrEnumeralTypes =
6562 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6563
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006564 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6565 PointerTypes.insert(Ty);
6566 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006567 // Insert our type, and its more-qualified variants, into the set
6568 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006569 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006570 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00006571 } else if (Ty->isMemberPointerType()) {
6572 // Member pointers are far easier, since the pointee can't be converted.
6573 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6574 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006575 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006576 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00006577 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006578 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006579 // We treat vector types as arithmetic types in many contexts as an
6580 // extension.
6581 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00006582 VectorTypes.insert(Ty);
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006583 } else if (Ty->isNullPtrType()) {
6584 HasNullPtrType = true;
Chandler Carruth6a577462010-12-13 01:44:01 +00006585 } else if (AllowUserConversions && TyRec) {
6586 // No conversion functions in incomplete types.
6587 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6588 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006589
Chandler Carruth6a577462010-12-13 01:44:01 +00006590 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006591 std::pair<CXXRecordDecl::conversion_iterator,
6592 CXXRecordDecl::conversion_iterator>
6593 Conversions = ClassDecl->getVisibleConversionFunctions();
6594 for (CXXRecordDecl::conversion_iterator
6595 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006596 NamedDecl *D = I.getDecl();
6597 if (isa<UsingShadowDecl>(D))
6598 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006599
Chandler Carruth6a577462010-12-13 01:44:01 +00006600 // Skip conversion function templates; they don't tell us anything
6601 // about which builtin types we can convert to.
6602 if (isa<FunctionTemplateDecl>(D))
6603 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006604
Chandler Carruth6a577462010-12-13 01:44:01 +00006605 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6606 if (AllowExplicitConversions || !Conv->isExplicit()) {
6607 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6608 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006609 }
6610 }
6611 }
6612}
6613
Douglas Gregor19b7b152009-08-24 13:43:27 +00006614/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6615/// the volatile- and non-volatile-qualified assignment operators for the
6616/// given type to the candidate set.
6617static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6618 QualType T,
Richard Smith958ba642013-05-05 15:51:06 +00006619 ArrayRef<Expr *> Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006620 OverloadCandidateSet &CandidateSet) {
6621 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00006622
Douglas Gregor19b7b152009-08-24 13:43:27 +00006623 // T& operator=(T&, T)
6624 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6625 ParamTypes[1] = T;
Richard Smith958ba642013-05-05 15:51:06 +00006626 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006627 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00006628
Douglas Gregor19b7b152009-08-24 13:43:27 +00006629 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6630 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00006631 ParamTypes[0]
6632 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00006633 ParamTypes[1] = T;
Richard Smith958ba642013-05-05 15:51:06 +00006634 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00006635 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00006636 }
6637}
Mike Stump1eb44332009-09-09 15:08:12 +00006638
Sebastian Redl9994a342009-10-25 17:03:50 +00006639/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6640/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006641static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6642 Qualifiers VRQuals;
6643 const RecordType *TyRec;
6644 if (const MemberPointerType *RHSMPType =
6645 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00006646 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006647 else
6648 TyRec = ArgExpr->getType()->getAs<RecordType>();
6649 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006650 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006651 VRQuals.addVolatile();
6652 VRQuals.addRestrict();
6653 return VRQuals;
6654 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006655
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006656 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00006657 if (!ClassDecl->hasDefinition())
6658 return VRQuals;
6659
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006660 std::pair<CXXRecordDecl::conversion_iterator,
6661 CXXRecordDecl::conversion_iterator>
6662 Conversions = ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006663
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006664 for (CXXRecordDecl::conversion_iterator
6665 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00006666 NamedDecl *D = I.getDecl();
6667 if (isa<UsingShadowDecl>(D))
6668 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6669 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006670 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6671 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6672 CanTy = ResTypeRef->getPointeeType();
6673 // Need to go down the pointer/mempointer chain and add qualifiers
6674 // as see them.
6675 bool done = false;
6676 while (!done) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006677 if (CanTy.isRestrictQualified())
6678 VRQuals.addRestrict();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006679 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6680 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006681 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006682 CanTy->getAs<MemberPointerType>())
6683 CanTy = ResTypeMPtr->getPointeeType();
6684 else
6685 done = true;
6686 if (CanTy.isVolatileQualified())
6687 VRQuals.addVolatile();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006688 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6689 return VRQuals;
6690 }
6691 }
6692 }
6693 return VRQuals;
6694}
John McCall00071ec2010-11-13 05:51:15 +00006695
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006696namespace {
John McCall00071ec2010-11-13 05:51:15 +00006697
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006698/// \brief Helper class to manage the addition of builtin operator overload
6699/// candidates. It provides shared state and utility methods used throughout
6700/// the process, as well as a helper method to add each group of builtin
6701/// operator overloads from the standard to a candidate set.
6702class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00006703 // Common instance state available to all overload candidate addition methods.
6704 Sema &S;
Richard Smith958ba642013-05-05 15:51:06 +00006705 ArrayRef<Expr *> Args;
Chandler Carruth6d695582010-12-12 10:35:00 +00006706 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00006707 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006708 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruth6d695582010-12-12 10:35:00 +00006709 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006710
Chandler Carruth6d695582010-12-12 10:35:00 +00006711 // Define some constants used to index and iterate over the arithemetic types
6712 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00006713 // The "promoted arithmetic types" are the arithmetic
6714 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00006715 static const unsigned FirstIntegralType = 3;
Richard Smith3c2fcf82012-06-10 08:00:26 +00006716 static const unsigned LastIntegralType = 20;
John McCall00071ec2010-11-13 05:51:15 +00006717 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006718 LastPromotedIntegralType = 11;
John McCall00071ec2010-11-13 05:51:15 +00006719 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006720 LastPromotedArithmeticType = 11;
6721 static const unsigned NumArithmeticTypes = 20;
John McCall00071ec2010-11-13 05:51:15 +00006722
Chandler Carruth6d695582010-12-12 10:35:00 +00006723 /// \brief Get the canonical type for a given arithmetic type index.
6724 CanQualType getArithmeticType(unsigned index) {
6725 assert(index < NumArithmeticTypes);
6726 static CanQualType ASTContext::* const
6727 ArithmeticTypes[NumArithmeticTypes] = {
6728 // Start of promoted types.
6729 &ASTContext::FloatTy,
6730 &ASTContext::DoubleTy,
6731 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00006732
Chandler Carruth6d695582010-12-12 10:35:00 +00006733 // Start of integral types.
6734 &ASTContext::IntTy,
6735 &ASTContext::LongTy,
6736 &ASTContext::LongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006737 &ASTContext::Int128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006738 &ASTContext::UnsignedIntTy,
6739 &ASTContext::UnsignedLongTy,
6740 &ASTContext::UnsignedLongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006741 &ASTContext::UnsignedInt128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006742 // End of promoted types.
6743
6744 &ASTContext::BoolTy,
6745 &ASTContext::CharTy,
6746 &ASTContext::WCharTy,
6747 &ASTContext::Char16Ty,
6748 &ASTContext::Char32Ty,
6749 &ASTContext::SignedCharTy,
6750 &ASTContext::ShortTy,
6751 &ASTContext::UnsignedCharTy,
6752 &ASTContext::UnsignedShortTy,
6753 // End of integral types.
Richard Smith3c2fcf82012-06-10 08:00:26 +00006754 // FIXME: What about complex? What about half?
Chandler Carruth6d695582010-12-12 10:35:00 +00006755 };
6756 return S.Context.*ArithmeticTypes[index];
6757 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006758
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006759 /// \brief Gets the canonical type resulting from the usual arithemetic
6760 /// converions for the given arithmetic types.
6761 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6762 // Accelerator table for performing the usual arithmetic conversions.
6763 // The rules are basically:
6764 // - if either is floating-point, use the wider floating-point
6765 // - if same signedness, use the higher rank
6766 // - if same size, use unsigned of the higher rank
6767 // - use the larger type
6768 // These rules, together with the axiom that higher ranks are
6769 // never smaller, are sufficient to precompute all of these results
6770 // *except* when dealing with signed types of higher rank.
6771 // (we could precompute SLL x UI for all known platforms, but it's
6772 // better not to make any assumptions).
Richard Smith3c2fcf82012-06-10 08:00:26 +00006773 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006774 enum PromotedType {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006775 Dep=-1,
6776 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006777 };
Nuno Lopes79e244f2012-04-21 14:45:25 +00006778 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006779 [LastPromotedArithmeticType] = {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006780/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6781/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6782/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6783/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6784/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6785/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6786/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6787/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6788/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6789/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6790/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006791 };
6792
6793 assert(L < LastPromotedArithmeticType);
6794 assert(R < LastPromotedArithmeticType);
6795 int Idx = ConversionsTable[L][R];
6796
6797 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00006798 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006799
6800 // Slow path: we need to compare widths.
6801 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00006802 CanQualType LT = getArithmeticType(L),
6803 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006804 unsigned LW = S.Context.getIntWidth(LT),
6805 RW = S.Context.getIntWidth(RT);
6806
6807 // If they're different widths, use the signed type.
6808 if (LW > RW) return LT;
6809 else if (LW < RW) return RT;
6810
6811 // Otherwise, use the unsigned type of the signed type's rank.
6812 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6813 assert(L == SLL || R == SLL);
6814 return S.Context.UnsignedLongLongTy;
6815 }
6816
Chandler Carruth3c69dc42010-12-12 09:22:45 +00006817 /// \brief Helper method to factor out the common pattern of adding overloads
6818 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006819 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006820 bool HasVolatile,
6821 bool HasRestrict) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006822 QualType ParamTypes[2] = {
6823 S.Context.getLValueReferenceType(CandidateTy),
6824 S.Context.IntTy
6825 };
6826
6827 // Non-volatile version.
Richard Smith958ba642013-05-05 15:51:06 +00006828 if (Args.size() == 1)
6829 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006830 else
Richard Smith958ba642013-05-05 15:51:06 +00006831 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006832
6833 // Use a heuristic to reduce number of builtin candidates in the set:
6834 // add volatile version only if there are conversions to a volatile type.
6835 if (HasVolatile) {
6836 ParamTypes[0] =
6837 S.Context.getLValueReferenceType(
6838 S.Context.getVolatileType(CandidateTy));
Richard Smith958ba642013-05-05 15:51:06 +00006839 if (Args.size() == 1)
6840 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006841 else
Richard Smith958ba642013-05-05 15:51:06 +00006842 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006843 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006844
6845 // Add restrict version only if there are conversions to a restrict type
6846 // and our candidate type is a non-restrict-qualified pointer.
6847 if (HasRestrict && CandidateTy->isAnyPointerType() &&
6848 !CandidateTy.isRestrictQualified()) {
6849 ParamTypes[0]
6850 = S.Context.getLValueReferenceType(
6851 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smith958ba642013-05-05 15:51:06 +00006852 if (Args.size() == 1)
6853 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006854 else
Richard Smith958ba642013-05-05 15:51:06 +00006855 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006856
6857 if (HasVolatile) {
6858 ParamTypes[0]
6859 = S.Context.getLValueReferenceType(
6860 S.Context.getCVRQualifiedType(CandidateTy,
6861 (Qualifiers::Volatile |
6862 Qualifiers::Restrict)));
Richard Smith958ba642013-05-05 15:51:06 +00006863 if (Args.size() == 1)
6864 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006865 else
Richard Smith958ba642013-05-05 15:51:06 +00006866 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006867 }
6868 }
6869
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006870 }
6871
6872public:
6873 BuiltinOperatorOverloadBuilder(
Richard Smith958ba642013-05-05 15:51:06 +00006874 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006875 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00006876 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006877 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006878 OverloadCandidateSet &CandidateSet)
Richard Smith958ba642013-05-05 15:51:06 +00006879 : S(S), Args(Args),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006880 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00006881 HasArithmeticOrEnumeralCandidateType(
6882 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006883 CandidateTypes(CandidateTypes),
6884 CandidateSet(CandidateSet) {
6885 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00006886 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006887 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006888 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006889 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006890 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006891 assert(getArithmeticType(FirstPromotedArithmeticType)
6892 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006893 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006894 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006895 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006896 "Invalid last promoted arithmetic type");
6897 }
6898
6899 // C++ [over.built]p3:
6900 //
6901 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6902 // is either volatile or empty, there exist candidate operator
6903 // functions of the form
6904 //
6905 // VQ T& operator++(VQ T&);
6906 // T operator++(VQ T&, int);
6907 //
6908 // C++ [over.built]p4:
6909 //
6910 // For every pair (T, VQ), where T is an arithmetic type other
6911 // than bool, and VQ is either volatile or empty, there exist
6912 // candidate operator functions of the form
6913 //
6914 // VQ T& operator--(VQ T&);
6915 // T operator--(VQ T&, int);
6916 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006917 if (!HasArithmeticOrEnumeralCandidateType)
6918 return;
6919
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006920 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6921 Arith < NumArithmeticTypes; ++Arith) {
6922 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00006923 getArithmeticType(Arith),
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006924 VisibleTypeConversionsQuals.hasVolatile(),
6925 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006926 }
6927 }
6928
6929 // C++ [over.built]p5:
6930 //
6931 // For every pair (T, VQ), where T is a cv-qualified or
6932 // cv-unqualified object type, and VQ is either volatile or
6933 // empty, there exist candidate operator functions of the form
6934 //
6935 // T*VQ& operator++(T*VQ&);
6936 // T*VQ& operator--(T*VQ&);
6937 // T* operator++(T*VQ&, int);
6938 // T* operator--(T*VQ&, int);
6939 void addPlusPlusMinusMinusPointerOverloads() {
6940 for (BuiltinCandidateTypeSet::iterator
6941 Ptr = CandidateTypes[0].pointer_begin(),
6942 PtrEnd = CandidateTypes[0].pointer_end();
6943 Ptr != PtrEnd; ++Ptr) {
6944 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006945 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006946 continue;
6947
6948 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006949 (!(*Ptr).isVolatileQualified() &&
6950 VisibleTypeConversionsQuals.hasVolatile()),
6951 (!(*Ptr).isRestrictQualified() &&
6952 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006953 }
6954 }
6955
6956 // C++ [over.built]p6:
6957 // For every cv-qualified or cv-unqualified object type T, there
6958 // exist candidate operator functions of the form
6959 //
6960 // T& operator*(T*);
6961 //
6962 // C++ [over.built]p7:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006963 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006964 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006965 // T& operator*(T*);
6966 void addUnaryStarPointerOverloads() {
6967 for (BuiltinCandidateTypeSet::iterator
6968 Ptr = CandidateTypes[0].pointer_begin(),
6969 PtrEnd = CandidateTypes[0].pointer_end();
6970 Ptr != PtrEnd; ++Ptr) {
6971 QualType ParamTy = *Ptr;
6972 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006973 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6974 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006975
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006976 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6977 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6978 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006979
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006980 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smith958ba642013-05-05 15:51:06 +00006981 &ParamTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006982 }
6983 }
6984
6985 // C++ [over.built]p9:
6986 // For every promoted arithmetic type T, there exist candidate
6987 // operator functions of the form
6988 //
6989 // T operator+(T);
6990 // T operator-(T);
6991 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006992 if (!HasArithmeticOrEnumeralCandidateType)
6993 return;
6994
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006995 for (unsigned Arith = FirstPromotedArithmeticType;
6996 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006997 QualType ArithTy = getArithmeticType(Arith);
Richard Smith958ba642013-05-05 15:51:06 +00006998 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006999 }
7000
7001 // Extension: We also add these operators for vector types.
7002 for (BuiltinCandidateTypeSet::iterator
7003 Vec = CandidateTypes[0].vector_begin(),
7004 VecEnd = CandidateTypes[0].vector_end();
7005 Vec != VecEnd; ++Vec) {
7006 QualType VecTy = *Vec;
Richard Smith958ba642013-05-05 15:51:06 +00007007 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007008 }
7009 }
7010
7011 // C++ [over.built]p8:
7012 // For every type T, there exist candidate operator functions of
7013 // the form
7014 //
7015 // T* operator+(T*);
7016 void addUnaryPlusPointerOverloads() {
7017 for (BuiltinCandidateTypeSet::iterator
7018 Ptr = CandidateTypes[0].pointer_begin(),
7019 PtrEnd = CandidateTypes[0].pointer_end();
7020 Ptr != PtrEnd; ++Ptr) {
7021 QualType ParamTy = *Ptr;
Richard Smith958ba642013-05-05 15:51:06 +00007022 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007023 }
7024 }
7025
7026 // C++ [over.built]p10:
7027 // For every promoted integral type T, there exist candidate
7028 // operator functions of the form
7029 //
7030 // T operator~(T);
7031 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00007032 if (!HasArithmeticOrEnumeralCandidateType)
7033 return;
7034
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007035 for (unsigned Int = FirstPromotedIntegralType;
7036 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007037 QualType IntTy = getArithmeticType(Int);
Richard Smith958ba642013-05-05 15:51:06 +00007038 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007039 }
7040
7041 // Extension: We also add this operator for vector types.
7042 for (BuiltinCandidateTypeSet::iterator
7043 Vec = CandidateTypes[0].vector_begin(),
7044 VecEnd = CandidateTypes[0].vector_end();
7045 Vec != VecEnd; ++Vec) {
7046 QualType VecTy = *Vec;
Richard Smith958ba642013-05-05 15:51:06 +00007047 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007048 }
7049 }
7050
7051 // C++ [over.match.oper]p16:
7052 // For every pointer to member type T, there exist candidate operator
7053 // functions of the form
7054 //
7055 // bool operator==(T,T);
7056 // bool operator!=(T,T);
7057 void addEqualEqualOrNotEqualMemberPointerOverloads() {
7058 /// Set of (canonical) types that we've already handled.
7059 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7060
Richard Smith958ba642013-05-05 15:51:06 +00007061 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007062 for (BuiltinCandidateTypeSet::iterator
7063 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7064 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7065 MemPtr != MemPtrEnd;
7066 ++MemPtr) {
7067 // Don't add the same builtin candidate twice.
7068 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7069 continue;
7070
7071 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smith958ba642013-05-05 15:51:06 +00007072 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007073 }
7074 }
7075 }
7076
7077 // C++ [over.built]p15:
7078 //
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00007079 // For every T, where T is an enumeration type, a pointer type, or
7080 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007081 //
7082 // bool operator<(T, T);
7083 // bool operator>(T, T);
7084 // bool operator<=(T, T);
7085 // bool operator>=(T, T);
7086 // bool operator==(T, T);
7087 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007088 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman97c67392012-09-18 21:52:24 +00007089 // C++ [over.match.oper]p3:
7090 // [...]the built-in candidates include all of the candidate operator
7091 // functions defined in 13.6 that, compared to the given operator, [...]
7092 // do not have the same parameter-type-list as any non-template non-member
7093 // candidate.
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007094 //
Eli Friedman97c67392012-09-18 21:52:24 +00007095 // Note that in practice, this only affects enumeration types because there
7096 // aren't any built-in candidates of record type, and a user-defined operator
7097 // must have an operand of record or enumeration type. Also, the only other
7098 // overloaded operator with enumeration arguments, operator=,
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007099 // cannot be overloaded for enumeration types, so this is the only place
7100 // where we must suppress candidates like this.
7101 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7102 UserDefinedBinaryOperators;
7103
Richard Smith958ba642013-05-05 15:51:06 +00007104 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007105 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7106 CandidateTypes[ArgIdx].enumeration_end()) {
7107 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7108 CEnd = CandidateSet.end();
7109 C != CEnd; ++C) {
7110 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7111 continue;
7112
Eli Friedman97c67392012-09-18 21:52:24 +00007113 if (C->Function->isFunctionTemplateSpecialization())
7114 continue;
7115
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007116 QualType FirstParamType =
7117 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7118 QualType SecondParamType =
7119 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7120
7121 // Skip if either parameter isn't of enumeral type.
7122 if (!FirstParamType->isEnumeralType() ||
7123 !SecondParamType->isEnumeralType())
7124 continue;
7125
7126 // Add this operator to the set of known user-defined operators.
7127 UserDefinedBinaryOperators.insert(
7128 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7129 S.Context.getCanonicalType(SecondParamType)));
7130 }
7131 }
7132 }
7133
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007134 /// Set of (canonical) types that we've already handled.
7135 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7136
Richard Smith958ba642013-05-05 15:51:06 +00007137 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007138 for (BuiltinCandidateTypeSet::iterator
7139 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7140 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7141 Ptr != PtrEnd; ++Ptr) {
7142 // Don't add the same builtin candidate twice.
7143 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7144 continue;
7145
7146 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smith958ba642013-05-05 15:51:06 +00007147 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007148 }
7149 for (BuiltinCandidateTypeSet::iterator
7150 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7151 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7152 Enum != EnumEnd; ++Enum) {
7153 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7154
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007155 // Don't add the same builtin candidate twice, or if a user defined
7156 // candidate exists.
7157 if (!AddedTypes.insert(CanonType) ||
7158 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7159 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007160 continue;
7161
7162 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smith958ba642013-05-05 15:51:06 +00007163 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007164 }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00007165
7166 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7167 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7168 if (AddedTypes.insert(NullPtrTy) &&
Richard Smith958ba642013-05-05 15:51:06 +00007169 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00007170 NullPtrTy))) {
7171 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smith958ba642013-05-05 15:51:06 +00007172 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00007173 CandidateSet);
7174 }
7175 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007176 }
7177 }
7178
7179 // C++ [over.built]p13:
7180 //
7181 // For every cv-qualified or cv-unqualified object type T
7182 // there exist candidate operator functions of the form
7183 //
7184 // T* operator+(T*, ptrdiff_t);
7185 // T& operator[](T*, ptrdiff_t); [BELOW]
7186 // T* operator-(T*, ptrdiff_t);
7187 // T* operator+(ptrdiff_t, T*);
7188 // T& operator[](ptrdiff_t, T*); [BELOW]
7189 //
7190 // C++ [over.built]p14:
7191 //
7192 // For every T, where T is a pointer to object type, there
7193 // exist candidate operator functions of the form
7194 //
7195 // ptrdiff_t operator-(T, T);
7196 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7197 /// Set of (canonical) types that we've already handled.
7198 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7199
7200 for (int Arg = 0; Arg < 2; ++Arg) {
7201 QualType AsymetricParamTypes[2] = {
7202 S.Context.getPointerDiffType(),
7203 S.Context.getPointerDiffType(),
7204 };
7205 for (BuiltinCandidateTypeSet::iterator
7206 Ptr = CandidateTypes[Arg].pointer_begin(),
7207 PtrEnd = CandidateTypes[Arg].pointer_end();
7208 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007209 QualType PointeeTy = (*Ptr)->getPointeeType();
7210 if (!PointeeTy->isObjectType())
7211 continue;
7212
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007213 AsymetricParamTypes[Arg] = *Ptr;
7214 if (Arg == 0 || Op == OO_Plus) {
7215 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7216 // T* operator+(ptrdiff_t, T*);
Richard Smith958ba642013-05-05 15:51:06 +00007217 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007218 }
7219 if (Op == OO_Minus) {
7220 // ptrdiff_t operator-(T, T);
7221 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7222 continue;
7223
7224 QualType ParamTypes[2] = { *Ptr, *Ptr };
7225 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smith958ba642013-05-05 15:51:06 +00007226 Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007227 }
7228 }
7229 }
7230 }
7231
7232 // C++ [over.built]p12:
7233 //
7234 // For every pair of promoted arithmetic types L and R, there
7235 // exist candidate operator functions of the form
7236 //
7237 // LR operator*(L, R);
7238 // LR operator/(L, R);
7239 // LR operator+(L, R);
7240 // LR operator-(L, R);
7241 // bool operator<(L, R);
7242 // bool operator>(L, R);
7243 // bool operator<=(L, R);
7244 // bool operator>=(L, R);
7245 // bool operator==(L, R);
7246 // bool operator!=(L, R);
7247 //
7248 // where LR is the result of the usual arithmetic conversions
7249 // between types L and R.
7250 //
7251 // C++ [over.built]p24:
7252 //
7253 // For every pair of promoted arithmetic types L and R, there exist
7254 // candidate operator functions of the form
7255 //
7256 // LR operator?(bool, L, R);
7257 //
7258 // where LR is the result of the usual arithmetic conversions
7259 // between types L and R.
7260 // Our candidates ignore the first parameter.
7261 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007262 if (!HasArithmeticOrEnumeralCandidateType)
7263 return;
7264
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007265 for (unsigned Left = FirstPromotedArithmeticType;
7266 Left < LastPromotedArithmeticType; ++Left) {
7267 for (unsigned Right = FirstPromotedArithmeticType;
7268 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007269 QualType LandR[2] = { getArithmeticType(Left),
7270 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007271 QualType Result =
7272 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007273 : getUsualArithmeticConversions(Left, Right);
Richard Smith958ba642013-05-05 15:51:06 +00007274 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007275 }
7276 }
7277
7278 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7279 // conditional operator for vector types.
7280 for (BuiltinCandidateTypeSet::iterator
7281 Vec1 = CandidateTypes[0].vector_begin(),
7282 Vec1End = CandidateTypes[0].vector_end();
7283 Vec1 != Vec1End; ++Vec1) {
7284 for (BuiltinCandidateTypeSet::iterator
7285 Vec2 = CandidateTypes[1].vector_begin(),
7286 Vec2End = CandidateTypes[1].vector_end();
7287 Vec2 != Vec2End; ++Vec2) {
7288 QualType LandR[2] = { *Vec1, *Vec2 };
7289 QualType Result = S.Context.BoolTy;
7290 if (!isComparison) {
7291 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7292 Result = *Vec1;
7293 else
7294 Result = *Vec2;
7295 }
7296
Richard Smith958ba642013-05-05 15:51:06 +00007297 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007298 }
7299 }
7300 }
7301
7302 // C++ [over.built]p17:
7303 //
7304 // For every pair of promoted integral types L and R, there
7305 // exist candidate operator functions of the form
7306 //
7307 // LR operator%(L, R);
7308 // LR operator&(L, R);
7309 // LR operator^(L, R);
7310 // LR operator|(L, R);
7311 // L operator<<(L, R);
7312 // L operator>>(L, R);
7313 //
7314 // where LR is the result of the usual arithmetic conversions
7315 // between types L and R.
7316 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007317 if (!HasArithmeticOrEnumeralCandidateType)
7318 return;
7319
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007320 for (unsigned Left = FirstPromotedIntegralType;
7321 Left < LastPromotedIntegralType; ++Left) {
7322 for (unsigned Right = FirstPromotedIntegralType;
7323 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007324 QualType LandR[2] = { getArithmeticType(Left),
7325 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007326 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7327 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007328 : getUsualArithmeticConversions(Left, Right);
Richard Smith958ba642013-05-05 15:51:06 +00007329 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007330 }
7331 }
7332 }
7333
7334 // C++ [over.built]p20:
7335 //
7336 // For every pair (T, VQ), where T is an enumeration or
7337 // pointer to member type and VQ is either volatile or
7338 // empty, there exist candidate operator functions of the form
7339 //
7340 // VQ T& operator=(VQ T&, T);
7341 void addAssignmentMemberPointerOrEnumeralOverloads() {
7342 /// Set of (canonical) types that we've already handled.
7343 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7344
7345 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7346 for (BuiltinCandidateTypeSet::iterator
7347 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7348 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7349 Enum != EnumEnd; ++Enum) {
7350 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7351 continue;
7352
Richard Smith958ba642013-05-05 15:51:06 +00007353 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007354 }
7355
7356 for (BuiltinCandidateTypeSet::iterator
7357 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7358 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7359 MemPtr != MemPtrEnd; ++MemPtr) {
7360 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7361 continue;
7362
Richard Smith958ba642013-05-05 15:51:06 +00007363 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007364 }
7365 }
7366 }
7367
7368 // C++ [over.built]p19:
7369 //
7370 // For every pair (T, VQ), where T is any type and VQ is either
7371 // volatile or empty, there exist candidate operator functions
7372 // of the form
7373 //
7374 // T*VQ& operator=(T*VQ&, T*);
7375 //
7376 // C++ [over.built]p21:
7377 //
7378 // For every pair (T, VQ), where T is a cv-qualified or
7379 // cv-unqualified object type and VQ is either volatile or
7380 // empty, there exist candidate operator functions of the form
7381 //
7382 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7383 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7384 void addAssignmentPointerOverloads(bool isEqualOp) {
7385 /// Set of (canonical) types that we've already handled.
7386 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7387
7388 for (BuiltinCandidateTypeSet::iterator
7389 Ptr = CandidateTypes[0].pointer_begin(),
7390 PtrEnd = CandidateTypes[0].pointer_end();
7391 Ptr != PtrEnd; ++Ptr) {
7392 // If this is operator=, keep track of the builtin candidates we added.
7393 if (isEqualOp)
7394 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007395 else if (!(*Ptr)->getPointeeType()->isObjectType())
7396 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007397
7398 // non-volatile version
7399 QualType ParamTypes[2] = {
7400 S.Context.getLValueReferenceType(*Ptr),
7401 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7402 };
Richard Smith958ba642013-05-05 15:51:06 +00007403 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007404 /*IsAssigmentOperator=*/ isEqualOp);
7405
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007406 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7407 VisibleTypeConversionsQuals.hasVolatile();
7408 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007409 // volatile version
7410 ParamTypes[0] =
7411 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007412 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007413 /*IsAssigmentOperator=*/isEqualOp);
7414 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007415
7416 if (!(*Ptr).isRestrictQualified() &&
7417 VisibleTypeConversionsQuals.hasRestrict()) {
7418 // restrict version
7419 ParamTypes[0]
7420 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007421 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007422 /*IsAssigmentOperator=*/isEqualOp);
7423
7424 if (NeedVolatile) {
7425 // volatile restrict version
7426 ParamTypes[0]
7427 = S.Context.getLValueReferenceType(
7428 S.Context.getCVRQualifiedType(*Ptr,
7429 (Qualifiers::Volatile |
7430 Qualifiers::Restrict)));
Richard Smith958ba642013-05-05 15:51:06 +00007431 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007432 /*IsAssigmentOperator=*/isEqualOp);
7433 }
7434 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007435 }
7436
7437 if (isEqualOp) {
7438 for (BuiltinCandidateTypeSet::iterator
7439 Ptr = CandidateTypes[1].pointer_begin(),
7440 PtrEnd = CandidateTypes[1].pointer_end();
7441 Ptr != PtrEnd; ++Ptr) {
7442 // Make sure we don't add the same candidate twice.
7443 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7444 continue;
7445
Chandler Carruth6df868e2010-12-12 08:17:55 +00007446 QualType ParamTypes[2] = {
7447 S.Context.getLValueReferenceType(*Ptr),
7448 *Ptr,
7449 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007450
7451 // non-volatile version
Richard Smith958ba642013-05-05 15:51:06 +00007452 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007453 /*IsAssigmentOperator=*/true);
7454
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007455 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7456 VisibleTypeConversionsQuals.hasVolatile();
7457 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007458 // volatile version
7459 ParamTypes[0] =
7460 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007461 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7462 /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007463 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007464
7465 if (!(*Ptr).isRestrictQualified() &&
7466 VisibleTypeConversionsQuals.hasRestrict()) {
7467 // restrict version
7468 ParamTypes[0]
7469 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007470 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7471 /*IsAssigmentOperator=*/true);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007472
7473 if (NeedVolatile) {
7474 // volatile restrict version
7475 ParamTypes[0]
7476 = S.Context.getLValueReferenceType(
7477 S.Context.getCVRQualifiedType(*Ptr,
7478 (Qualifiers::Volatile |
7479 Qualifiers::Restrict)));
Richard Smith958ba642013-05-05 15:51:06 +00007480 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7481 /*IsAssigmentOperator=*/true);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007482 }
7483 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007484 }
7485 }
7486 }
7487
7488 // C++ [over.built]p18:
7489 //
7490 // For every triple (L, VQ, R), where L is an arithmetic type,
7491 // VQ is either volatile or empty, and R is a promoted
7492 // arithmetic type, there exist candidate operator functions of
7493 // the form
7494 //
7495 // VQ L& operator=(VQ L&, R);
7496 // VQ L& operator*=(VQ L&, R);
7497 // VQ L& operator/=(VQ L&, R);
7498 // VQ L& operator+=(VQ L&, R);
7499 // VQ L& operator-=(VQ L&, R);
7500 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007501 if (!HasArithmeticOrEnumeralCandidateType)
7502 return;
7503
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007504 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7505 for (unsigned Right = FirstPromotedArithmeticType;
7506 Right < LastPromotedArithmeticType; ++Right) {
7507 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007508 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007509
7510 // Add this built-in operator as a candidate (VQ is empty).
7511 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007512 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smith958ba642013-05-05 15:51:06 +00007513 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007514 /*IsAssigmentOperator=*/isEqualOp);
7515
7516 // Add this built-in operator as a candidate (VQ is 'volatile').
7517 if (VisibleTypeConversionsQuals.hasVolatile()) {
7518 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007519 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007520 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smith958ba642013-05-05 15:51:06 +00007521 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007522 /*IsAssigmentOperator=*/isEqualOp);
7523 }
7524 }
7525 }
7526
7527 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7528 for (BuiltinCandidateTypeSet::iterator
7529 Vec1 = CandidateTypes[0].vector_begin(),
7530 Vec1End = CandidateTypes[0].vector_end();
7531 Vec1 != Vec1End; ++Vec1) {
7532 for (BuiltinCandidateTypeSet::iterator
7533 Vec2 = CandidateTypes[1].vector_begin(),
7534 Vec2End = CandidateTypes[1].vector_end();
7535 Vec2 != Vec2End; ++Vec2) {
7536 QualType ParamTypes[2];
7537 ParamTypes[1] = *Vec2;
7538 // Add this built-in operator as a candidate (VQ is empty).
7539 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smith958ba642013-05-05 15:51:06 +00007540 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007541 /*IsAssigmentOperator=*/isEqualOp);
7542
7543 // Add this built-in operator as a candidate (VQ is 'volatile').
7544 if (VisibleTypeConversionsQuals.hasVolatile()) {
7545 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7546 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smith958ba642013-05-05 15:51:06 +00007547 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007548 /*IsAssigmentOperator=*/isEqualOp);
7549 }
7550 }
7551 }
7552 }
7553
7554 // C++ [over.built]p22:
7555 //
7556 // For every triple (L, VQ, R), where L is an integral type, VQ
7557 // is either volatile or empty, and R is a promoted integral
7558 // type, there exist candidate operator functions of the form
7559 //
7560 // VQ L& operator%=(VQ L&, R);
7561 // VQ L& operator<<=(VQ L&, R);
7562 // VQ L& operator>>=(VQ L&, R);
7563 // VQ L& operator&=(VQ L&, R);
7564 // VQ L& operator^=(VQ L&, R);
7565 // VQ L& operator|=(VQ L&, R);
7566 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00007567 if (!HasArithmeticOrEnumeralCandidateType)
7568 return;
7569
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007570 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7571 for (unsigned Right = FirstPromotedIntegralType;
7572 Right < LastPromotedIntegralType; ++Right) {
7573 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007574 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007575
7576 // Add this built-in operator as a candidate (VQ is empty).
7577 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007578 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smith958ba642013-05-05 15:51:06 +00007579 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007580 if (VisibleTypeConversionsQuals.hasVolatile()) {
7581 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00007582 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007583 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7584 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smith958ba642013-05-05 15:51:06 +00007585 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007586 }
7587 }
7588 }
7589 }
7590
7591 // C++ [over.operator]p23:
7592 //
7593 // There also exist candidate operator functions of the form
7594 //
7595 // bool operator!(bool);
7596 // bool operator&&(bool, bool);
7597 // bool operator||(bool, bool);
7598 void addExclaimOverload() {
7599 QualType ParamTy = S.Context.BoolTy;
Richard Smith958ba642013-05-05 15:51:06 +00007600 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007601 /*IsAssignmentOperator=*/false,
7602 /*NumContextualBoolArguments=*/1);
7603 }
7604 void addAmpAmpOrPipePipeOverload() {
7605 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smith958ba642013-05-05 15:51:06 +00007606 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007607 /*IsAssignmentOperator=*/false,
7608 /*NumContextualBoolArguments=*/2);
7609 }
7610
7611 // C++ [over.built]p13:
7612 //
7613 // For every cv-qualified or cv-unqualified object type T there
7614 // exist candidate operator functions of the form
7615 //
7616 // T* operator+(T*, ptrdiff_t); [ABOVE]
7617 // T& operator[](T*, ptrdiff_t);
7618 // T* operator-(T*, ptrdiff_t); [ABOVE]
7619 // T* operator+(ptrdiff_t, T*); [ABOVE]
7620 // T& operator[](ptrdiff_t, T*);
7621 void addSubscriptOverloads() {
7622 for (BuiltinCandidateTypeSet::iterator
7623 Ptr = CandidateTypes[0].pointer_begin(),
7624 PtrEnd = CandidateTypes[0].pointer_end();
7625 Ptr != PtrEnd; ++Ptr) {
7626 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7627 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007628 if (!PointeeType->isObjectType())
7629 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007630
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007631 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7632
7633 // T& operator[](T*, ptrdiff_t)
Richard Smith958ba642013-05-05 15:51:06 +00007634 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007635 }
7636
7637 for (BuiltinCandidateTypeSet::iterator
7638 Ptr = CandidateTypes[1].pointer_begin(),
7639 PtrEnd = CandidateTypes[1].pointer_end();
7640 Ptr != PtrEnd; ++Ptr) {
7641 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7642 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007643 if (!PointeeType->isObjectType())
7644 continue;
7645
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007646 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7647
7648 // T& operator[](ptrdiff_t, T*)
Richard Smith958ba642013-05-05 15:51:06 +00007649 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007650 }
7651 }
7652
7653 // C++ [over.built]p11:
7654 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7655 // C1 is the same type as C2 or is a derived class of C2, T is an object
7656 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7657 // there exist candidate operator functions of the form
7658 //
7659 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7660 //
7661 // where CV12 is the union of CV1 and CV2.
7662 void addArrowStarOverloads() {
7663 for (BuiltinCandidateTypeSet::iterator
7664 Ptr = CandidateTypes[0].pointer_begin(),
7665 PtrEnd = CandidateTypes[0].pointer_end();
7666 Ptr != PtrEnd; ++Ptr) {
7667 QualType C1Ty = (*Ptr);
7668 QualType C1;
7669 QualifierCollector Q1;
7670 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7671 if (!isa<RecordType>(C1))
7672 continue;
7673 // heuristic to reduce number of builtin candidates in the set.
7674 // Add volatile/restrict version only if there are conversions to a
7675 // volatile/restrict type.
7676 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7677 continue;
7678 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7679 continue;
7680 for (BuiltinCandidateTypeSet::iterator
7681 MemPtr = CandidateTypes[1].member_pointer_begin(),
7682 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7683 MemPtr != MemPtrEnd; ++MemPtr) {
7684 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7685 QualType C2 = QualType(mptr->getClass(), 0);
7686 C2 = C2.getUnqualifiedType();
7687 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7688 break;
7689 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7690 // build CV12 T&
7691 QualType T = mptr->getPointeeType();
7692 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7693 T.isVolatileQualified())
7694 continue;
7695 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7696 T.isRestrictQualified())
7697 continue;
7698 T = Q1.apply(S.Context, T);
7699 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smith958ba642013-05-05 15:51:06 +00007700 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007701 }
7702 }
7703 }
7704
7705 // Note that we don't consider the first argument, since it has been
7706 // contextually converted to bool long ago. The candidates below are
7707 // therefore added as binary.
7708 //
7709 // C++ [over.built]p25:
7710 // For every type T, where T is a pointer, pointer-to-member, or scoped
7711 // enumeration type, there exist candidate operator functions of the form
7712 //
7713 // T operator?(bool, T, T);
7714 //
7715 void addConditionalOperatorOverloads() {
7716 /// Set of (canonical) types that we've already handled.
7717 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7718
7719 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7720 for (BuiltinCandidateTypeSet::iterator
7721 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7722 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7723 Ptr != PtrEnd; ++Ptr) {
7724 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7725 continue;
7726
7727 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smith958ba642013-05-05 15:51:06 +00007728 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007729 }
7730
7731 for (BuiltinCandidateTypeSet::iterator
7732 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7733 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7734 MemPtr != MemPtrEnd; ++MemPtr) {
7735 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7736 continue;
7737
7738 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smith958ba642013-05-05 15:51:06 +00007739 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007740 }
7741
Richard Smith80ad52f2013-01-02 11:42:31 +00007742 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007743 for (BuiltinCandidateTypeSet::iterator
7744 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7745 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7746 Enum != EnumEnd; ++Enum) {
7747 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7748 continue;
7749
7750 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7751 continue;
7752
7753 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smith958ba642013-05-05 15:51:06 +00007754 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007755 }
7756 }
7757 }
7758 }
7759};
7760
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007761} // end anonymous namespace
7762
7763/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7764/// operator overloads to the candidate set (C++ [over.built]), based
7765/// on the operator @p Op and the arguments given. For example, if the
7766/// operator is a binary '+', this routine might add "int
7767/// operator+(int, int)" to cover integer addition.
Robert Wilhelm834c0582013-08-09 18:02:13 +00007768void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7769 SourceLocation OpLoc,
7770 ArrayRef<Expr *> Args,
7771 OverloadCandidateSet &CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007772 // Find all of the types that the arguments can convert to, but only
7773 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00007774 // that make use of these types. Also record whether we encounter non-record
7775 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00007776 Qualifiers VisibleTypeConversionsQuals;
7777 VisibleTypeConversionsQuals.addConst();
Richard Smith958ba642013-05-05 15:51:06 +00007778 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanian8621d012009-10-19 21:30:45 +00007779 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00007780
7781 bool HasNonRecordCandidateType = false;
7782 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00007783 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smith958ba642013-05-05 15:51:06 +00007784 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorfec56e72010-11-03 17:00:07 +00007785 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7786 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7787 OpLoc,
7788 true,
7789 (Op == OO_Exclaim ||
7790 Op == OO_AmpAmp ||
7791 Op == OO_PipePipe),
7792 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00007793 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7794 CandidateTypes[ArgIdx].hasNonRecordTypes();
7795 HasArithmeticOrEnumeralCandidateType =
7796 HasArithmeticOrEnumeralCandidateType ||
7797 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00007798 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007799
Chandler Carruth6a577462010-12-13 01:44:01 +00007800 // Exit early when no non-record types have been added to the candidate set
7801 // for any of the arguments to the operator.
Douglas Gregor25aaff92011-10-10 14:05:31 +00007802 //
7803 // We can't exit early for !, ||, or &&, since there we have always have
7804 // 'bool' overloads.
Richard Smith958ba642013-05-05 15:51:06 +00007805 if (!HasNonRecordCandidateType &&
Douglas Gregor25aaff92011-10-10 14:05:31 +00007806 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth6a577462010-12-13 01:44:01 +00007807 return;
7808
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007809 // Setup an object to manage the common state for building overloads.
Richard Smith958ba642013-05-05 15:51:06 +00007810 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007811 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00007812 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007813 CandidateTypes, CandidateSet);
7814
7815 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007816 switch (Op) {
7817 case OO_None:
7818 case NUM_OVERLOADED_OPERATORS:
David Blaikieb219cfc2011-09-23 05:06:16 +00007819 llvm_unreachable("Expected an overloaded operator");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007820
Chandler Carruthabb71842010-12-12 08:51:33 +00007821 case OO_New:
7822 case OO_Delete:
7823 case OO_Array_New:
7824 case OO_Array_Delete:
7825 case OO_Call:
David Blaikieb219cfc2011-09-23 05:06:16 +00007826 llvm_unreachable(
7827 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruthabb71842010-12-12 08:51:33 +00007828
7829 case OO_Comma:
7830 case OO_Arrow:
7831 // C++ [over.match.oper]p3:
7832 // -- For the operator ',', the unary operator '&', or the
7833 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00007834 break;
7835
7836 case OO_Plus: // '+' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007837 if (Args.size() == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007838 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007839 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00007840
7841 case OO_Minus: // '-' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007842 if (Args.size() == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007843 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007844 } else {
7845 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7846 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7847 }
Douglas Gregor74253732008-11-19 15:42:04 +00007848 break;
7849
Chandler Carruthabb71842010-12-12 08:51:33 +00007850 case OO_Star: // '*' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007851 if (Args.size() == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007852 OpBuilder.addUnaryStarPointerOverloads();
7853 else
7854 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7855 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007856
Chandler Carruthabb71842010-12-12 08:51:33 +00007857 case OO_Slash:
7858 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00007859 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007860
7861 case OO_PlusPlus:
7862 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007863 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7864 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00007865 break;
7866
Douglas Gregor19b7b152009-08-24 13:43:27 +00007867 case OO_EqualEqual:
7868 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007869 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007870 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00007871
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007872 case OO_Less:
7873 case OO_Greater:
7874 case OO_LessEqual:
7875 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007876 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007877 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7878 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007879
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007880 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007881 case OO_Caret:
7882 case OO_Pipe:
7883 case OO_LessLess:
7884 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007885 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007886 break;
7887
Chandler Carruthabb71842010-12-12 08:51:33 +00007888 case OO_Amp: // '&' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007889 if (Args.size() == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007890 // C++ [over.match.oper]p3:
7891 // -- For the operator ',', the unary operator '&', or the
7892 // operator '->', the built-in candidates set is empty.
7893 break;
7894
7895 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7896 break;
7897
7898 case OO_Tilde:
7899 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7900 break;
7901
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007902 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007903 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00007904 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007905
7906 case OO_PlusEqual:
7907 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007908 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007909 // Fall through.
7910
7911 case OO_StarEqual:
7912 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007913 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007914 break;
7915
7916 case OO_PercentEqual:
7917 case OO_LessLessEqual:
7918 case OO_GreaterGreaterEqual:
7919 case OO_AmpEqual:
7920 case OO_CaretEqual:
7921 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007922 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007923 break;
7924
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007925 case OO_Exclaim:
7926 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00007927 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007928
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007929 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007930 case OO_PipePipe:
7931 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007932 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007933
7934 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007935 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007936 break;
7937
7938 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007939 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007940 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007941
7942 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007943 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007944 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7945 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007946 }
7947}
7948
Douglas Gregorfa047642009-02-04 00:32:51 +00007949/// \brief Add function candidates found via argument-dependent lookup
7950/// to the set of overloading candidates.
7951///
7952/// This routine performs argument-dependent name lookup based on the
7953/// given function name (which may also be an operator name) and adds
7954/// all of the overload candidates found by ADL to the overload
7955/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00007956void
Douglas Gregorfa047642009-02-04 00:32:51 +00007957Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00007958 bool Operator, SourceLocation Loc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00007959 ArrayRef<Expr *> Args,
Douglas Gregor67714232011-03-03 02:41:12 +00007960 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007961 OverloadCandidateSet& CandidateSet,
Richard Smithb1502bc2012-10-18 17:56:02 +00007962 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00007963 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00007964
John McCalla113e722010-01-26 06:04:06 +00007965 // FIXME: This approach for uniquing ADL results (and removing
7966 // redundant candidates from the set) relies on pointer-equality,
7967 // which means we need to key off the canonical decl. However,
7968 // always going back to the canonical decl might not get us the
7969 // right set of default arguments. What default arguments are
7970 // we supposed to consider on ADL candidates, anyway?
7971
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007972 // FIXME: Pass in the explicit template arguments?
Richard Smithb1502bc2012-10-18 17:56:02 +00007973 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00007974
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007975 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007976 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7977 CandEnd = CandidateSet.end();
7978 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00007979 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00007980 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00007981 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00007982 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00007983 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007984
7985 // For each of the ADL candidates we found, add it to the overload
7986 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00007987 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00007988 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00007989 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00007990 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007991 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007992
Ahmed Charles13a140c2012-02-25 11:00:22 +00007993 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7994 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007995 } else
John McCall6e266892010-01-26 03:27:55 +00007996 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00007997 FoundDecl, ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00007998 Args, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00007999 }
Douglas Gregorfa047642009-02-04 00:32:51 +00008000}
8001
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008002/// isBetterOverloadCandidate - Determines whether the first overload
8003/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00008004bool
John McCall120d63c2010-08-24 20:38:10 +00008005isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00008006 const OverloadCandidate &Cand1,
8007 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00008008 SourceLocation Loc,
8009 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008010 // Define viable functions to be better candidates than non-viable
8011 // functions.
8012 if (!Cand2.Viable)
8013 return Cand1.Viable;
8014 else if (!Cand1.Viable)
8015 return false;
8016
Douglas Gregor88a35142008-12-22 05:46:06 +00008017 // C++ [over.match.best]p1:
8018 //
8019 // -- if F is a static member function, ICS1(F) is defined such
8020 // that ICS1(F) is neither better nor worse than ICS1(G) for
8021 // any function G, and, symmetrically, ICS1(G) is neither
8022 // better nor worse than ICS1(F).
8023 unsigned StartArg = 0;
8024 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8025 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008026
Douglas Gregor3e15cc32009-07-07 23:38:56 +00008027 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00008028 // A viable function F1 is defined to be a better function than another
8029 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00008030 // conversion sequence than ICSi(F2), and then...
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008031 unsigned NumArgs = Cand1.NumConversions;
8032 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008033 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00008034 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00008035 switch (CompareImplicitConversionSequences(S,
8036 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008037 Cand2.Conversions[ArgIdx])) {
8038 case ImplicitConversionSequence::Better:
8039 // Cand1 has a better conversion sequence.
8040 HasBetterConversion = true;
8041 break;
8042
8043 case ImplicitConversionSequence::Worse:
8044 // Cand1 can't be better than Cand2.
8045 return false;
8046
8047 case ImplicitConversionSequence::Indistinguishable:
8048 // Do nothing.
8049 break;
8050 }
8051 }
8052
Mike Stump1eb44332009-09-09 15:08:12 +00008053 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00008054 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008055 if (HasBetterConversion)
8056 return true;
8057
Mike Stump1eb44332009-09-09 15:08:12 +00008058 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00008059 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00008060 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00008061 Cand2.Function && Cand2.Function->getPrimaryTemplate())
8062 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00008063
8064 // -- F1 and F2 are function template specializations, and the function
8065 // template for F1 is more specialized than the template for F2
8066 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00008067 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00008068 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregordfc331e2011-01-19 23:54:39 +00008069 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00008070 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00008071 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8072 Cand2.Function->getPrimaryTemplate(),
8073 Loc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008074 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00008075 : TPOC_Call,
Richard Smith66118c22013-09-11 00:52:39 +00008076 Cand1.ExplicitCallArguments,
8077 Cand2.ExplicitCallArguments))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00008078 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregordfc331e2011-01-19 23:54:39 +00008079 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008080
Douglas Gregorf1991ea2008-11-07 22:36:19 +00008081 // -- the context is an initialization by user-defined conversion
8082 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8083 // from the return type of F1 to the destination type (i.e.,
8084 // the type of the entity being initialized) is a better
8085 // conversion sequence than the standard conversion sequence
8086 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00008087 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00008088 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00008089 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregorb734e242012-02-22 17:32:19 +00008090 // First check whether we prefer one of the conversion functions over the
8091 // other. This only distinguishes the results in non-standard, extension
8092 // cases such as the conversion from a lambda closure type to a function
8093 // pointer or block.
8094 ImplicitConversionSequence::CompareKind FuncResult
8095 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8096 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
8097 return FuncResult;
8098
John McCall120d63c2010-08-24 20:38:10 +00008099 switch (CompareStandardConversionSequences(S,
8100 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00008101 Cand2.FinalConversion)) {
8102 case ImplicitConversionSequence::Better:
8103 // Cand1 has a better conversion sequence.
8104 return true;
8105
8106 case ImplicitConversionSequence::Worse:
8107 // Cand1 can't be better than Cand2.
8108 return false;
8109
8110 case ImplicitConversionSequence::Indistinguishable:
8111 // Do nothing
8112 break;
8113 }
8114 }
8115
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008116 return false;
8117}
8118
Mike Stump1eb44332009-09-09 15:08:12 +00008119/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00008120/// within an overload candidate set.
8121///
James Dennettefce31f2012-06-22 08:10:18 +00008122/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregore0762c92009-06-19 23:52:42 +00008123/// which overload resolution occurs.
8124///
James Dennettefce31f2012-06-22 08:10:18 +00008125/// \param Best If overload resolution was successful or found a deleted
8126/// function, \p Best points to the candidate function found.
Douglas Gregore0762c92009-06-19 23:52:42 +00008127///
8128/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00008129OverloadingResult
8130OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00008131 iterator &Best,
Chandler Carruth25ca4212011-02-25 19:41:05 +00008132 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008133 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00008134 Best = end();
8135 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8136 if (Cand->Viable)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008137 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00008138 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008139 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008140 }
8141
8142 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00008143 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008144 return OR_No_Viable_Function;
8145
8146 // Make sure that this function is better than every other viable
8147 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00008148 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00008149 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008150 Cand != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008151 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00008152 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00008153 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008154 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008155 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008156 }
Mike Stump1eb44332009-09-09 15:08:12 +00008157
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008158 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008159 if (Best->Function &&
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008160 (Best->Function->isDeleted() ||
8161 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008162 return OR_Deleted;
8163
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008164 return OR_Success;
8165}
8166
John McCall3c80f572010-01-12 02:15:36 +00008167namespace {
8168
8169enum OverloadCandidateKind {
8170 oc_function,
8171 oc_method,
8172 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00008173 oc_function_template,
8174 oc_method_template,
8175 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00008176 oc_implicit_default_constructor,
8177 oc_implicit_copy_constructor,
Sean Hunt82713172011-05-25 23:16:36 +00008178 oc_implicit_move_constructor,
Sebastian Redlf677ea32011-02-05 19:23:19 +00008179 oc_implicit_copy_assignment,
Sean Hunt82713172011-05-25 23:16:36 +00008180 oc_implicit_move_assignment,
Sebastian Redlf677ea32011-02-05 19:23:19 +00008181 oc_implicit_inherited_constructor
John McCall3c80f572010-01-12 02:15:36 +00008182};
8183
John McCall220ccbf2010-01-13 00:25:19 +00008184OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8185 FunctionDecl *Fn,
8186 std::string &Description) {
8187 bool isTemplate = false;
8188
8189 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8190 isTemplate = true;
8191 Description = S.getTemplateArgumentBindingsText(
8192 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8193 }
John McCallb1622a12010-01-06 09:43:14 +00008194
8195 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00008196 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00008197 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00008198
Sebastian Redlf677ea32011-02-05 19:23:19 +00008199 if (Ctor->getInheritedConstructor())
8200 return oc_implicit_inherited_constructor;
8201
Sean Hunt82713172011-05-25 23:16:36 +00008202 if (Ctor->isDefaultConstructor())
8203 return oc_implicit_default_constructor;
8204
8205 if (Ctor->isMoveConstructor())
8206 return oc_implicit_move_constructor;
8207
8208 assert(Ctor->isCopyConstructor() &&
8209 "unexpected sort of implicit constructor");
8210 return oc_implicit_copy_constructor;
John McCallb1622a12010-01-06 09:43:14 +00008211 }
8212
8213 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8214 // This actually gets spelled 'candidate function' for now, but
8215 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00008216 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00008217 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00008218
Sean Hunt82713172011-05-25 23:16:36 +00008219 if (Meth->isMoveAssignmentOperator())
8220 return oc_implicit_move_assignment;
8221
Douglas Gregoref7d78b2012-02-10 08:36:38 +00008222 if (Meth->isCopyAssignmentOperator())
8223 return oc_implicit_copy_assignment;
8224
8225 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8226 return oc_method;
John McCall3c80f572010-01-12 02:15:36 +00008227 }
8228
John McCall220ccbf2010-01-13 00:25:19 +00008229 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00008230}
8231
Larisse Voufo43847122013-07-19 23:00:19 +00008232void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
Sebastian Redlf677ea32011-02-05 19:23:19 +00008233 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8234 if (!Ctor) return;
8235
8236 Ctor = Ctor->getInheritedConstructor();
8237 if (!Ctor) return;
8238
8239 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8240}
8241
John McCall3c80f572010-01-12 02:15:36 +00008242} // end anonymous namespace
8243
8244// Notes the location of an overload candidate.
Richard Trieu6efd4c52011-11-23 22:32:32 +00008245void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCall220ccbf2010-01-13 00:25:19 +00008246 std::string FnDesc;
8247 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieu6efd4c52011-11-23 22:32:32 +00008248 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8249 << (unsigned) K << FnDesc;
8250 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8251 Diag(Fn->getLocation(), PD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008252 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallb1622a12010-01-06 09:43:14 +00008253}
8254
Nick Lewycky199e3702013-09-22 10:06:01 +00008255// Notes the location of all overload candidates designated through
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008256// OverloadedExpr
Richard Trieu6efd4c52011-11-23 22:32:32 +00008257void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008258 assert(OverloadedExpr->getType() == Context.OverloadTy);
8259
8260 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8261 OverloadExpr *OvlExpr = Ovl.Expression;
8262
8263 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8264 IEnd = OvlExpr->decls_end();
8265 I != IEnd; ++I) {
8266 if (FunctionTemplateDecl *FunTmpl =
8267 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00008268 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008269 } else if (FunctionDecl *Fun
8270 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00008271 NoteOverloadCandidate(Fun, DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008272 }
8273 }
8274}
8275
John McCall1d318332010-01-12 00:44:57 +00008276/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8277/// "lead" diagnostic; it will be given two arguments, the source and
8278/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00008279void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8280 Sema &S,
8281 SourceLocation CaretLoc,
8282 const PartialDiagnostic &PDiag) const {
8283 S.Diag(CaretLoc, PDiag)
8284 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay45a37da2012-11-08 20:50:02 +00008285 // FIXME: The note limiting machinery is borrowed from
8286 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8287 // refactoring here.
8288 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8289 unsigned CandsShown = 0;
8290 AmbiguousConversionSequence::const_iterator I, E;
8291 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8292 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8293 break;
8294 ++CandsShown;
John McCall120d63c2010-08-24 20:38:10 +00008295 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00008296 }
Matt Beaumont-Gay45a37da2012-11-08 20:50:02 +00008297 if (I != E)
8298 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall81201622010-01-08 04:41:39 +00008299}
8300
John McCall1d318332010-01-12 00:44:57 +00008301namespace {
8302
John McCalladbb8f82010-01-13 09:16:55 +00008303void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8304 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8305 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00008306 assert(Cand->Function && "for now, candidate must be a function");
8307 FunctionDecl *Fn = Cand->Function;
8308
8309 // There's a conversion slot for the object argument if this is a
8310 // non-constructor method. Note that 'I' corresponds the
8311 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00008312 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00008313 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00008314 if (I == 0)
8315 isObjectArgument = true;
8316 else
8317 I--;
John McCall220ccbf2010-01-13 00:25:19 +00008318 }
8319
John McCall220ccbf2010-01-13 00:25:19 +00008320 std::string FnDesc;
8321 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8322
John McCalladbb8f82010-01-13 09:16:55 +00008323 Expr *FromExpr = Conv.Bad.FromExpr;
8324 QualType FromTy = Conv.Bad.getFromType();
8325 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00008326
John McCall5920dbb2010-02-02 02:42:52 +00008327 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00008328 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00008329 Expr *E = FromExpr->IgnoreParens();
8330 if (isa<UnaryOperator>(E))
8331 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00008332 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00008333
8334 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8335 << (unsigned) FnKind << FnDesc
8336 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8337 << ToTy << Name << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008338 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall5920dbb2010-02-02 02:42:52 +00008339 return;
8340 }
8341
John McCall258b2032010-01-23 08:10:49 +00008342 // Do some hand-waving analysis to see if the non-viability is due
8343 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00008344 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8345 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8346 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8347 CToTy = RT->getPointeeType();
8348 else {
8349 // TODO: detect and diagnose the full richness of const mismatches.
8350 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8351 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8352 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8353 }
8354
8355 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8356 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall651f3ee2010-01-14 03:28:57 +00008357 Qualifiers FromQs = CFromTy.getQualifiers();
8358 Qualifiers ToQs = CToTy.getQualifiers();
8359
8360 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8361 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8362 << (unsigned) FnKind << FnDesc
8363 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8364 << FromTy
8365 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8366 << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008367 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008368 return;
8369 }
8370
John McCallf85e1932011-06-15 23:02:42 +00008371 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00008372 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCallf85e1932011-06-15 23:02:42 +00008373 << (unsigned) FnKind << FnDesc
8374 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8375 << FromTy
8376 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8377 << (unsigned) isObjectArgument << I+1;
8378 MaybeEmitInheritedConstructorNote(S, Fn);
8379 return;
8380 }
8381
Douglas Gregor028ea4b2011-04-26 23:16:46 +00008382 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8383 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8384 << (unsigned) FnKind << FnDesc
8385 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8386 << FromTy
8387 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8388 << (unsigned) isObjectArgument << I+1;
8389 MaybeEmitInheritedConstructorNote(S, Fn);
8390 return;
8391 }
8392
John McCall651f3ee2010-01-14 03:28:57 +00008393 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8394 assert(CVR && "unexpected qualifiers mismatch");
8395
8396 if (isObjectArgument) {
8397 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8398 << (unsigned) FnKind << FnDesc
8399 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8400 << FromTy << (CVR - 1);
8401 } else {
8402 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8403 << (unsigned) FnKind << FnDesc
8404 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8405 << FromTy << (CVR - 1) << I+1;
8406 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008407 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008408 return;
8409 }
8410
Sebastian Redlfd2a00a2011-09-24 17:48:32 +00008411 // Special diagnostic for failure to convert an initializer list, since
8412 // telling the user that it has type void is not useful.
8413 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8414 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8415 << (unsigned) FnKind << FnDesc
8416 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8417 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8418 MaybeEmitInheritedConstructorNote(S, Fn);
8419 return;
8420 }
8421
John McCall258b2032010-01-23 08:10:49 +00008422 // Diagnose references or pointers to incomplete types differently,
8423 // since it's far from impossible that the incompleteness triggered
8424 // the failure.
8425 QualType TempFromTy = FromTy.getNonReferenceType();
8426 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8427 TempFromTy = PTy->getPointeeType();
8428 if (TempFromTy->isIncompleteType()) {
8429 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8430 << (unsigned) FnKind << FnDesc
8431 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8432 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008433 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall258b2032010-01-23 08:10:49 +00008434 return;
8435 }
8436
Douglas Gregor85789812010-06-30 23:01:39 +00008437 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008438 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00008439 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8440 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8441 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8442 FromPtrTy->getPointeeType()) &&
8443 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8444 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008445 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor85789812010-06-30 23:01:39 +00008446 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008447 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00008448 }
8449 } else if (const ObjCObjectPointerType *FromPtrTy
8450 = FromTy->getAs<ObjCObjectPointerType>()) {
8451 if (const ObjCObjectPointerType *ToPtrTy
8452 = ToTy->getAs<ObjCObjectPointerType>())
8453 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8454 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8455 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8456 FromPtrTy->getPointeeType()) &&
8457 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008458 BaseToDerivedConversion = 2;
8459 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008460 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8461 !FromTy->isIncompleteType() &&
8462 !ToRefTy->getPointeeType()->isIncompleteType() &&
8463 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8464 BaseToDerivedConversion = 3;
8465 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8466 ToTy.getNonReferenceType().getCanonicalType() ==
8467 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008468 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8469 << (unsigned) FnKind << FnDesc
8470 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8471 << (unsigned) isObjectArgument << I + 1;
8472 MaybeEmitInheritedConstructorNote(S, Fn);
8473 return;
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008474 }
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008475 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008476
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008477 if (BaseToDerivedConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008478 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008479 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00008480 << (unsigned) FnKind << FnDesc
8481 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008482 << (BaseToDerivedConversion - 1)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008483 << FromTy << ToTy << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008484 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor85789812010-06-30 23:01:39 +00008485 return;
8486 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008487
Fariborz Jahanian909bcb32011-07-20 17:14:09 +00008488 if (isa<ObjCObjectPointerType>(CFromTy) &&
8489 isa<PointerType>(CToTy)) {
8490 Qualifiers FromQs = CFromTy.getQualifiers();
8491 Qualifiers ToQs = CToTy.getQualifiers();
8492 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8493 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8494 << (unsigned) FnKind << FnDesc
8495 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8496 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8497 MaybeEmitInheritedConstructorNote(S, Fn);
8498 return;
8499 }
8500 }
8501
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008502 // Emit the generic diagnostic and, optionally, add the hints to it.
8503 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8504 FDiag << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00008505 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008506 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8507 << (unsigned) (Cand->Fix.Kind);
8508
8509 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer1136ef02012-01-14 21:05:10 +00008510 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8511 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008512 FDiag << *HI;
8513 S.Diag(Fn->getLocation(), FDiag);
8514
Sebastian Redlf677ea32011-02-05 19:23:19 +00008515 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalladbb8f82010-01-13 09:16:55 +00008516}
8517
Larisse Voufo43847122013-07-19 23:00:19 +00008518/// Additional arity mismatch diagnosis specific to a function overload
8519/// candidates. This is not covered by the more general DiagnoseArityMismatch()
8520/// over a candidate in any candidate set.
8521bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8522 unsigned NumArgs) {
John McCalladbb8f82010-01-13 09:16:55 +00008523 FunctionDecl *Fn = Cand->Function;
John McCalladbb8f82010-01-13 09:16:55 +00008524 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008525
Douglas Gregor439d3c32011-05-05 00:13:13 +00008526 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo43847122013-07-19 23:00:19 +00008527 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor439d3c32011-05-05 00:13:13 +00008528 // right number of arguments, because only overloaded operators have
8529 // the weird behavior of overloading member and non-member functions.
8530 // Just don't report anything.
8531 if (Fn->isInvalidDecl() &&
8532 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo43847122013-07-19 23:00:19 +00008533 return true;
8534
8535 if (NumArgs < MinParams) {
8536 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8537 (Cand->FailureKind == ovl_fail_bad_deduction &&
8538 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8539 } else {
8540 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8541 (Cand->FailureKind == ovl_fail_bad_deduction &&
8542 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8543 }
8544
8545 return false;
8546}
8547
8548/// General arity mismatch diagnosis over a candidate in a candidate set.
8549void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
8550 assert(isa<FunctionDecl>(D) &&
8551 "The templated declaration should at least be a function"
8552 " when diagnosing bad template argument deduction due to too many"
8553 " or too few arguments");
8554
8555 FunctionDecl *Fn = cast<FunctionDecl>(D);
8556
8557 // TODO: treat calls to a missing default constructor as a special case
8558 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8559 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor439d3c32011-05-05 00:13:13 +00008560
John McCalladbb8f82010-01-13 09:16:55 +00008561 // at least / at most / exactly
8562 unsigned mode, modeCount;
8563 if (NumFormalArgs < MinParams) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008564 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00008565 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00008566 mode = 0; // "at least"
8567 else
8568 mode = 2; // "exactly"
8569 modeCount = MinParams;
8570 } else {
John McCalladbb8f82010-01-13 09:16:55 +00008571 if (MinParams != FnTy->getNumArgs())
8572 mode = 1; // "at most"
8573 else
8574 mode = 2; // "exactly"
8575 modeCount = FnTy->getNumArgs();
8576 }
8577
8578 std::string Description;
8579 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8580
Richard Smithf7b80562012-05-11 05:16:41 +00008581 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8582 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8583 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8584 << Fn->getParamDecl(0) << NumFormalArgs;
8585 else
8586 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8587 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8588 << modeCount << NumFormalArgs;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008589 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008590}
8591
Larisse Voufo43847122013-07-19 23:00:19 +00008592/// Arity mismatch diagnosis specific to a function overload candidate.
8593void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8594 unsigned NumFormalArgs) {
8595 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
8596 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
8597}
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008598
Larisse Voufo43847122013-07-19 23:00:19 +00008599TemplateDecl *getDescribedTemplate(Decl *Templated) {
8600 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
8601 return FD->getDescribedFunctionTemplate();
8602 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
8603 return RD->getDescribedClassTemplate();
8604
8605 llvm_unreachable("Unsupported: Getting the described template declaration"
8606 " for bad deduction diagnosis");
8607}
8608
8609/// Diagnose a failed template-argument deduction.
8610void DiagnoseBadDeduction(Sema &S, Decl *Templated,
8611 DeductionFailureInfo &DeductionFailure,
8612 unsigned NumArgs) {
8613 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00008614 NamedDecl *ParamD;
8615 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8616 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8617 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo43847122013-07-19 23:00:19 +00008618 switch (DeductionFailure.Result) {
John McCall342fec42010-02-01 18:53:26 +00008619 case Sema::TDK_Success:
8620 llvm_unreachable("TDK_success while diagnosing bad deduction");
8621
8622 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00008623 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo43847122013-07-19 23:00:19 +00008624 S.Diag(Templated->getLocation(),
8625 diag::note_ovl_candidate_incomplete_deduction)
8626 << ParamD->getDeclName();
8627 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall342fec42010-02-01 18:53:26 +00008628 return;
8629 }
8630
John McCall57e97782010-08-05 09:05:08 +00008631 case Sema::TDK_Underqualified: {
8632 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8633 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8634
Larisse Voufo43847122013-07-19 23:00:19 +00008635 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall57e97782010-08-05 09:05:08 +00008636
8637 // Param will have been canonicalized, but it should just be a
8638 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00008639 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00008640 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00008641 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00008642 assert(S.Context.hasSameType(Param, NonCanonParam));
8643
8644 // Arg has also been canonicalized, but there's nothing we can do
8645 // about that. It also doesn't matter as much, because it won't
8646 // have any template parameters in it (because deduction isn't
8647 // done on dependent types).
Larisse Voufo43847122013-07-19 23:00:19 +00008648 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall57e97782010-08-05 09:05:08 +00008649
Larisse Voufo43847122013-07-19 23:00:19 +00008650 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
8651 << ParamD->getDeclName() << Arg << NonCanonParam;
8652 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall57e97782010-08-05 09:05:08 +00008653 return;
8654 }
8655
8656 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00008657 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00008658 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008659 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008660 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008661 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008662 which = 1;
8663 else {
Douglas Gregora9333192010-05-08 17:41:32 +00008664 which = 2;
8665 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008666
Larisse Voufo43847122013-07-19 23:00:19 +00008667 S.Diag(Templated->getLocation(),
8668 diag::note_ovl_candidate_inconsistent_deduction)
8669 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
8670 << *DeductionFailure.getSecondArg();
8671 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregora9333192010-05-08 17:41:32 +00008672 return;
8673 }
Douglas Gregora18592e2010-05-08 18:13:28 +00008674
Douglas Gregorf1a84452010-05-08 19:15:54 +00008675 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008676 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregorf1a84452010-05-08 19:15:54 +00008677 if (ParamD->getDeclName())
Larisse Voufo43847122013-07-19 23:00:19 +00008678 S.Diag(Templated->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008679 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo43847122013-07-19 23:00:19 +00008680 << ParamD->getDeclName();
Douglas Gregorf1a84452010-05-08 19:15:54 +00008681 else {
8682 int index = 0;
8683 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8684 index = TTP->getIndex();
8685 else if (NonTypeTemplateParmDecl *NTTP
8686 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8687 index = NTTP->getIndex();
8688 else
8689 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo43847122013-07-19 23:00:19 +00008690 S.Diag(Templated->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008691 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo43847122013-07-19 23:00:19 +00008692 << (index + 1);
Douglas Gregorf1a84452010-05-08 19:15:54 +00008693 }
Larisse Voufo43847122013-07-19 23:00:19 +00008694 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregorf1a84452010-05-08 19:15:54 +00008695 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008696
Douglas Gregora18592e2010-05-08 18:13:28 +00008697 case Sema::TDK_TooManyArguments:
8698 case Sema::TDK_TooFewArguments:
Larisse Voufo43847122013-07-19 23:00:19 +00008699 DiagnoseArityMismatch(S, Templated, NumArgs);
Douglas Gregora18592e2010-05-08 18:13:28 +00008700 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00008701
8702 case Sema::TDK_InstantiationDepth:
Larisse Voufo43847122013-07-19 23:00:19 +00008703 S.Diag(Templated->getLocation(),
8704 diag::note_ovl_candidate_instantiation_depth);
8705 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregorec20f462010-05-08 20:07:26 +00008706 return;
8707
8708 case Sema::TDK_SubstitutionFailure: {
Richard Smithb8590f32012-05-07 09:03:25 +00008709 // Format the template argument list into the argument string.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008710 SmallString<128> TemplateArgString;
Richard Smithb8590f32012-05-07 09:03:25 +00008711 if (TemplateArgumentList *Args =
Larisse Voufo43847122013-07-19 23:00:19 +00008712 DeductionFailure.getTemplateArgumentList()) {
Richard Smithb8590f32012-05-07 09:03:25 +00008713 TemplateArgString = " ";
8714 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo43847122013-07-19 23:00:19 +00008715 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smithb8590f32012-05-07 09:03:25 +00008716 }
8717
Richard Smith4493c0a2012-05-09 05:17:00 +00008718 // If this candidate was disabled by enable_if, say so.
Larisse Voufo43847122013-07-19 23:00:19 +00008719 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith4493c0a2012-05-09 05:17:00 +00008720 if (PDiag && PDiag->second.getDiagID() ==
8721 diag::err_typename_nested_not_found_enable_if) {
8722 // FIXME: Use the source range of the condition, and the fully-qualified
8723 // name of the enable_if template. These are both present in PDiag.
8724 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8725 << "'enable_if'" << TemplateArgString;
8726 return;
8727 }
8728
Richard Smithb8590f32012-05-07 09:03:25 +00008729 // Format the SFINAE diagnostic into the argument string.
8730 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8731 // formatted message in another diagnostic.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008732 SmallString<128> SFINAEArgString;
Richard Smithb8590f32012-05-07 09:03:25 +00008733 SourceRange R;
Richard Smith4493c0a2012-05-09 05:17:00 +00008734 if (PDiag) {
Richard Smithb8590f32012-05-07 09:03:25 +00008735 SFINAEArgString = ": ";
8736 R = SourceRange(PDiag->first, PDiag->first);
8737 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8738 }
8739
Larisse Voufo43847122013-07-19 23:00:19 +00008740 S.Diag(Templated->getLocation(),
8741 diag::note_ovl_candidate_substitution_failure)
8742 << TemplateArgString << SFINAEArgString << R;
8743 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregorec20f462010-05-08 20:07:26 +00008744 return;
8745 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008746
Richard Smith0efa62f2013-01-31 04:03:12 +00008747 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo43847122013-07-19 23:00:19 +00008748 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
8749 S.Diag(Templated->getLocation(),
Richard Smith0efa62f2013-01-31 04:03:12 +00008750 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo43847122013-07-19 23:00:19 +00008751 << R.Expression->getName();
Richard Smith0efa62f2013-01-31 04:03:12 +00008752 return;
8753 }
8754
Richard Trieueef35f82013-04-08 21:11:40 +00008755 case Sema::TDK_NonDeducedMismatch: {
Richard Smith29805ca2013-01-31 05:19:49 +00008756 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo43847122013-07-19 23:00:19 +00008757 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
8758 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieueef35f82013-04-08 21:11:40 +00008759 if (FirstTA.getKind() == TemplateArgument::Template &&
8760 SecondTA.getKind() == TemplateArgument::Template) {
8761 TemplateName FirstTN = FirstTA.getAsTemplate();
8762 TemplateName SecondTN = SecondTA.getAsTemplate();
8763 if (FirstTN.getKind() == TemplateName::Template &&
8764 SecondTN.getKind() == TemplateName::Template) {
8765 if (FirstTN.getAsTemplateDecl()->getName() ==
8766 SecondTN.getAsTemplateDecl()->getName()) {
8767 // FIXME: This fixes a bad diagnostic where both templates are named
8768 // the same. This particular case is a bit difficult since:
8769 // 1) It is passed as a string to the diagnostic printer.
8770 // 2) The diagnostic printer only attempts to find a better
8771 // name for types, not decls.
8772 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo43847122013-07-19 23:00:19 +00008773 S.Diag(Templated->getLocation(),
Richard Trieueef35f82013-04-08 21:11:40 +00008774 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
8775 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
8776 return;
8777 }
8778 }
8779 }
Faisal Valifad9e132013-09-26 19:54:12 +00008780 // FIXME: For generic lambda parameters, check if the function is a lambda
8781 // call operator, and if so, emit a prettier and more informative
8782 // diagnostic that mentions 'auto' and lambda in addition to
8783 // (or instead of?) the canonical template type parameters.
Larisse Voufo43847122013-07-19 23:00:19 +00008784 S.Diag(Templated->getLocation(),
8785 diag::note_ovl_candidate_non_deduced_mismatch)
8786 << FirstTA << SecondTA;
Richard Smith29805ca2013-01-31 05:19:49 +00008787 return;
Richard Trieueef35f82013-04-08 21:11:40 +00008788 }
John McCall342fec42010-02-01 18:53:26 +00008789 // TODO: diagnose these individually, then kill off
8790 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith29805ca2013-01-31 05:19:49 +00008791 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo43847122013-07-19 23:00:19 +00008792 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
8793 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall342fec42010-02-01 18:53:26 +00008794 return;
8795 }
8796}
8797
Larisse Voufo43847122013-07-19 23:00:19 +00008798/// Diagnose a failed template-argument deduction, for function calls.
8799void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, unsigned NumArgs) {
8800 unsigned TDK = Cand->DeductionFailure.Result;
8801 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
8802 if (CheckArityMismatch(S, Cand, NumArgs))
8803 return;
8804 }
8805 DiagnoseBadDeduction(S, Cand->Function, // pattern
8806 Cand->DeductionFailure, NumArgs);
8807}
8808
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008809/// CUDA: diagnose an invalid call across targets.
8810void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8811 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8812 FunctionDecl *Callee = Cand->Function;
8813
8814 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8815 CalleeTarget = S.IdentifyCUDATarget(Callee);
8816
8817 std::string FnDesc;
8818 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8819
8820 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8821 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8822}
8823
John McCall342fec42010-02-01 18:53:26 +00008824/// Generates a 'note' diagnostic for an overload candidate. We've
8825/// already generated a primary error at the call site.
8826///
8827/// It really does need to be a single diagnostic with its caret
8828/// pointed at the candidate declaration. Yes, this creates some
8829/// major challenges of technical writing. Yes, this makes pointing
8830/// out problems with specific arguments quite awkward. It's still
8831/// better than generating twenty screens of text for every failed
8832/// overload.
8833///
8834/// It would be great to be able to express per-candidate problems
8835/// more richly for those diagnostic clients that cared, but we'd
8836/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00008837void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008838 unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00008839 FunctionDecl *Fn = Cand->Function;
8840
John McCall81201622010-01-08 04:41:39 +00008841 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008842 if (Cand->Viable && (Fn->isDeleted() ||
8843 S.isFunctionConsideredUnavailable(Fn))) {
John McCall220ccbf2010-01-13 00:25:19 +00008844 std::string FnDesc;
8845 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00008846
8847 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith5bdaac52012-04-02 20:59:25 +00008848 << FnKind << FnDesc
8849 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008850 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalla1d7d622010-01-08 00:58:21 +00008851 return;
John McCall81201622010-01-08 04:41:39 +00008852 }
8853
John McCall220ccbf2010-01-13 00:25:19 +00008854 // We don't really have anything else to say about viable candidates.
8855 if (Cand->Viable) {
8856 S.NoteOverloadCandidate(Fn);
8857 return;
8858 }
John McCall1d318332010-01-12 00:44:57 +00008859
John McCalladbb8f82010-01-13 09:16:55 +00008860 switch (Cand->FailureKind) {
8861 case ovl_fail_too_many_arguments:
8862 case ovl_fail_too_few_arguments:
8863 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00008864
John McCalladbb8f82010-01-13 09:16:55 +00008865 case ovl_fail_bad_deduction:
Ahmed Charles13a140c2012-02-25 11:00:22 +00008866 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall342fec42010-02-01 18:53:26 +00008867
John McCall717e8912010-01-23 05:17:32 +00008868 case ovl_fail_trivial_conversion:
8869 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00008870 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00008871 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008872
John McCallb1bdc622010-02-25 01:37:24 +00008873 case ovl_fail_bad_conversion: {
8874 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008875 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00008876 if (Cand->Conversions[I].isBad())
8877 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008878
John McCalladbb8f82010-01-13 09:16:55 +00008879 // FIXME: this currently happens when we're called from SemaInit
8880 // when user-conversion overload fails. Figure out how to handle
8881 // those conditions and diagnose them well.
8882 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008883 }
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008884
8885 case ovl_fail_bad_target:
8886 return DiagnoseBadTarget(S, Cand);
John McCallb1bdc622010-02-25 01:37:24 +00008887 }
John McCalla1d7d622010-01-08 00:58:21 +00008888}
8889
8890void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8891 // Desugar the type of the surrogate down to a function type,
8892 // retaining as many typedefs as possible while still showing
8893 // the function type (and, therefore, its parameter types).
8894 QualType FnType = Cand->Surrogate->getConversionType();
8895 bool isLValueReference = false;
8896 bool isRValueReference = false;
8897 bool isPointer = false;
8898 if (const LValueReferenceType *FnTypeRef =
8899 FnType->getAs<LValueReferenceType>()) {
8900 FnType = FnTypeRef->getPointeeType();
8901 isLValueReference = true;
8902 } else if (const RValueReferenceType *FnTypeRef =
8903 FnType->getAs<RValueReferenceType>()) {
8904 FnType = FnTypeRef->getPointeeType();
8905 isRValueReference = true;
8906 }
8907 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8908 FnType = FnTypePtr->getPointeeType();
8909 isPointer = true;
8910 }
8911 // Desugar down to a function type.
8912 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8913 // Reconstruct the pointer/reference as appropriate.
8914 if (isPointer) FnType = S.Context.getPointerType(FnType);
8915 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8916 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8917
8918 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8919 << FnType;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008920 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalla1d7d622010-01-08 00:58:21 +00008921}
8922
8923void NoteBuiltinOperatorCandidate(Sema &S,
David Blaikie0bea8632012-10-08 01:11:04 +00008924 StringRef Opc,
John McCalla1d7d622010-01-08 00:58:21 +00008925 SourceLocation OpLoc,
8926 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008927 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalla1d7d622010-01-08 00:58:21 +00008928 std::string TypeStr("operator");
8929 TypeStr += Opc;
8930 TypeStr += "(";
8931 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008932 if (Cand->NumConversions == 1) {
John McCalla1d7d622010-01-08 00:58:21 +00008933 TypeStr += ")";
8934 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8935 } else {
8936 TypeStr += ", ";
8937 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8938 TypeStr += ")";
8939 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8940 }
8941}
8942
8943void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8944 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008945 unsigned NoOperands = Cand->NumConversions;
John McCalla1d7d622010-01-08 00:58:21 +00008946 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8947 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00008948 if (ICS.isBad()) break; // all meaningless after first invalid
8949 if (!ICS.isAmbiguous()) continue;
8950
John McCall120d63c2010-08-24 20:38:10 +00008951 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008952 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00008953 }
8954}
8955
Larisse Voufo43847122013-07-19 23:00:19 +00008956static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall1b77e732010-01-15 23:32:50 +00008957 if (Cand->Function)
8958 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00008959 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00008960 return Cand->Surrogate->getLocation();
8961 return SourceLocation();
8962}
8963
Larisse Voufo43847122013-07-19 23:00:19 +00008964static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth78bf6802011-09-10 00:51:24 +00008965 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008966 case Sema::TDK_Success:
David Blaikieb219cfc2011-09-23 05:06:16 +00008967 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008968
Douglas Gregorae19fbb2012-09-13 21:01:57 +00008969 case Sema::TDK_Invalid:
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008970 case Sema::TDK_Incomplete:
8971 return 1;
8972
8973 case Sema::TDK_Underqualified:
8974 case Sema::TDK_Inconsistent:
8975 return 2;
8976
8977 case Sema::TDK_SubstitutionFailure:
8978 case Sema::TDK_NonDeducedMismatch:
Richard Smith29805ca2013-01-31 05:19:49 +00008979 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008980 return 3;
8981
8982 case Sema::TDK_InstantiationDepth:
8983 case Sema::TDK_FailedOverloadResolution:
8984 return 4;
8985
8986 case Sema::TDK_InvalidExplicitArguments:
8987 return 5;
8988
8989 case Sema::TDK_TooManyArguments:
8990 case Sema::TDK_TooFewArguments:
8991 return 6;
8992 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008993 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008994}
8995
John McCallbf65c0b2010-01-12 00:48:53 +00008996struct CompareOverloadCandidatesForDisplay {
8997 Sema &S;
8998 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00008999
9000 bool operator()(const OverloadCandidate *L,
9001 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00009002 // Fast-path this check.
9003 if (L == R) return false;
9004
John McCall81201622010-01-08 04:41:39 +00009005 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00009006 if (L->Viable) {
9007 if (!R->Viable) return true;
9008
9009 // TODO: introduce a tri-valued comparison for overload
9010 // candidates. Would be more worthwhile if we had a sort
9011 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00009012 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9013 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00009014 } else if (R->Viable)
9015 return false;
John McCall81201622010-01-08 04:41:39 +00009016
John McCall1b77e732010-01-15 23:32:50 +00009017 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00009018
John McCall1b77e732010-01-15 23:32:50 +00009019 // Criteria by which we can sort non-viable candidates:
9020 if (!L->Viable) {
9021 // 1. Arity mismatches come after other candidates.
9022 if (L->FailureKind == ovl_fail_too_many_arguments ||
9023 L->FailureKind == ovl_fail_too_few_arguments)
9024 return false;
9025 if (R->FailureKind == ovl_fail_too_many_arguments ||
9026 R->FailureKind == ovl_fail_too_few_arguments)
9027 return true;
John McCall81201622010-01-08 04:41:39 +00009028
John McCall717e8912010-01-23 05:17:32 +00009029 // 2. Bad conversions come first and are ordered by the number
9030 // of bad conversions and quality of good conversions.
9031 if (L->FailureKind == ovl_fail_bad_conversion) {
9032 if (R->FailureKind != ovl_fail_bad_conversion)
9033 return true;
9034
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009035 // The conversion that can be fixed with a smaller number of changes,
9036 // comes first.
9037 unsigned numLFixes = L->Fix.NumConversionsFixed;
9038 unsigned numRFixes = R->Fix.NumConversionsFixed;
9039 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9040 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaksffe9edd2011-07-21 00:34:39 +00009041 if (numLFixes != numRFixes) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009042 if (numLFixes < numRFixes)
9043 return true;
9044 else
9045 return false;
Anna Zaksffe9edd2011-07-21 00:34:39 +00009046 }
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009047
John McCall717e8912010-01-23 05:17:32 +00009048 // If there's any ordering between the defined conversions...
9049 // FIXME: this might not be transitive.
Benjamin Kramer09dd3792012-01-14 16:32:05 +00009050 assert(L->NumConversions == R->NumConversions);
John McCall717e8912010-01-23 05:17:32 +00009051
9052 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00009053 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00009054 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00009055 switch (CompareImplicitConversionSequences(S,
9056 L->Conversions[I],
9057 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00009058 case ImplicitConversionSequence::Better:
9059 leftBetter++;
9060 break;
9061
9062 case ImplicitConversionSequence::Worse:
9063 leftBetter--;
9064 break;
9065
9066 case ImplicitConversionSequence::Indistinguishable:
9067 break;
9068 }
9069 }
9070 if (leftBetter > 0) return true;
9071 if (leftBetter < 0) return false;
9072
9073 } else if (R->FailureKind == ovl_fail_bad_conversion)
9074 return false;
9075
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00009076 if (L->FailureKind == ovl_fail_bad_deduction) {
9077 if (R->FailureKind != ovl_fail_bad_deduction)
9078 return true;
9079
9080 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9081 return RankDeductionFailure(L->DeductionFailure)
Eli Friedmance1846e2011-10-14 23:10:30 +00009082 < RankDeductionFailure(R->DeductionFailure);
Eli Friedman1c522f72011-10-14 21:52:24 +00009083 } else if (R->FailureKind == ovl_fail_bad_deduction)
9084 return false;
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00009085
John McCall1b77e732010-01-15 23:32:50 +00009086 // TODO: others?
9087 }
9088
9089 // Sort everything else by location.
9090 SourceLocation LLoc = GetLocationForCandidate(L);
9091 SourceLocation RLoc = GetLocationForCandidate(R);
9092
9093 // Put candidates without locations (e.g. builtins) at the end.
9094 if (LLoc.isInvalid()) return false;
9095 if (RLoc.isInvalid()) return true;
9096
9097 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00009098 }
9099};
9100
John McCall717e8912010-01-23 05:17:32 +00009101/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009102/// computes up to the first. Produces the FixIt set if possible.
John McCall717e8912010-01-23 05:17:32 +00009103void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009104 ArrayRef<Expr *> Args) {
John McCall717e8912010-01-23 05:17:32 +00009105 assert(!Cand->Viable);
9106
9107 // Don't do anything on failures other than bad conversion.
9108 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9109
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009110 // We only want the FixIts if all the arguments can be corrected.
9111 bool Unfixable = false;
Anna Zaksf3546ee2011-07-28 19:46:48 +00009112 // Use a implicit copy initialization to check conversion fixes.
9113 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009114
John McCall717e8912010-01-23 05:17:32 +00009115 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00009116 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00009117 unsigned ConvCount = Cand->NumConversions;
John McCall717e8912010-01-23 05:17:32 +00009118 while (true) {
9119 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9120 ConvIdx++;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009121 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaksf3546ee2011-07-28 19:46:48 +00009122 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCall717e8912010-01-23 05:17:32 +00009123 break;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009124 }
John McCall717e8912010-01-23 05:17:32 +00009125 }
9126
9127 if (ConvIdx == ConvCount)
9128 return;
9129
John McCallb1bdc622010-02-25 01:37:24 +00009130 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9131 "remaining conversion is initialized?");
9132
Douglas Gregor23ef6c02010-04-16 17:45:54 +00009133 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00009134 // operation somehow.
9135 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00009136
9137 const FunctionProtoType* Proto;
9138 unsigned ArgIdx = ConvIdx;
9139
9140 if (Cand->IsSurrogate) {
9141 QualType ConvType
9142 = Cand->Surrogate->getConversionType().getNonReferenceType();
9143 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9144 ConvType = ConvPtrType->getPointeeType();
9145 Proto = ConvType->getAs<FunctionProtoType>();
9146 ArgIdx--;
9147 } else if (Cand->Function) {
9148 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9149 if (isa<CXXMethodDecl>(Cand->Function) &&
9150 !isa<CXXConstructorDecl>(Cand->Function))
9151 ArgIdx--;
9152 } else {
9153 // Builtin binary operator with a bad first conversion.
9154 assert(ConvCount <= 3);
9155 for (; ConvIdx != ConvCount; ++ConvIdx)
9156 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00009157 = TryCopyInitialization(S, Args[ConvIdx],
9158 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009159 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00009160 /*InOverloadResolution*/ true,
9161 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00009162 S.getLangOpts().ObjCAutoRefCount);
John McCall717e8912010-01-23 05:17:32 +00009163 return;
9164 }
9165
9166 // Fill in the rest of the conversions.
9167 unsigned NumArgsInProto = Proto->getNumArgs();
9168 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009169 if (ArgIdx < NumArgsInProto) {
John McCall717e8912010-01-23 05:17:32 +00009170 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00009171 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009172 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00009173 /*InOverloadResolution=*/true,
9174 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00009175 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009176 // Store the FixIt in the candidate if it exists.
9177 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaksf3546ee2011-07-28 19:46:48 +00009178 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009179 }
John McCall717e8912010-01-23 05:17:32 +00009180 else
9181 Cand->Conversions[ConvIdx].setEllipsis();
9182 }
9183}
9184
John McCalla1d7d622010-01-08 00:58:21 +00009185} // end anonymous namespace
9186
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00009187/// PrintOverloadCandidates - When overload resolution fails, prints
9188/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00009189/// set.
John McCall120d63c2010-08-24 20:38:10 +00009190void OverloadCandidateSet::NoteCandidates(Sema &S,
9191 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009192 ArrayRef<Expr *> Args,
David Blaikie0bea8632012-10-08 01:11:04 +00009193 StringRef Opc,
John McCall120d63c2010-08-24 20:38:10 +00009194 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00009195 // Sort the candidates by viability and position. Sorting directly would
9196 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00009197 SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00009198 if (OCD == OCD_AllCandidates) Cands.reserve(size());
9199 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00009200 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00009201 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00009202 else if (OCD == OCD_AllCandidates) {
Ahmed Charles13a140c2012-02-25 11:00:22 +00009203 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009204 if (Cand->Function || Cand->IsSurrogate)
9205 Cands.push_back(Cand);
9206 // Otherwise, this a non-viable builtin candidate. We do not, in general,
9207 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00009208 }
9209 }
9210
John McCallbf65c0b2010-01-12 00:48:53 +00009211 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00009212 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009213
John McCall1d318332010-01-12 00:44:57 +00009214 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00009215
Chris Lattner5f9e2722011-07-23 10:55:15 +00009216 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregordc7b6412012-10-23 23:11:23 +00009217 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009218 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00009219 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9220 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00009221
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009222 // Set an arbitrary limit on the number of candidate functions we'll spam
9223 // the user with. FIXME: This limit should depend on details of the
9224 // candidate list.
Douglas Gregordc7b6412012-10-23 23:11:23 +00009225 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009226 break;
9227 }
9228 ++CandsShown;
9229
John McCalla1d7d622010-01-08 00:58:21 +00009230 if (Cand->Function)
Ahmed Charles13a140c2012-02-25 11:00:22 +00009231 NoteFunctionCandidate(S, Cand, Args.size());
John McCalla1d7d622010-01-08 00:58:21 +00009232 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00009233 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009234 else {
9235 assert(Cand->Viable &&
9236 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00009237 // Generally we only see ambiguities including viable builtin
9238 // operators if overload resolution got screwed up by an
9239 // ambiguous user-defined conversion.
9240 //
9241 // FIXME: It's quite possible for different conversions to see
9242 // different ambiguities, though.
9243 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00009244 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00009245 ReportedAmbiguousConversions = true;
9246 }
John McCalla1d7d622010-01-08 00:58:21 +00009247
John McCall1d318332010-01-12 00:44:57 +00009248 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00009249 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00009250 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00009251 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009252
9253 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00009254 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00009255}
9256
Larisse Voufo43847122013-07-19 23:00:19 +00009257static SourceLocation
9258GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9259 return Cand->Specialization ? Cand->Specialization->getLocation()
9260 : SourceLocation();
9261}
9262
9263struct CompareTemplateSpecCandidatesForDisplay {
9264 Sema &S;
9265 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9266
9267 bool operator()(const TemplateSpecCandidate *L,
9268 const TemplateSpecCandidate *R) {
9269 // Fast-path this check.
9270 if (L == R)
9271 return false;
9272
9273 // Assuming that both candidates are not matches...
9274
9275 // Sort by the ranking of deduction failures.
9276 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9277 return RankDeductionFailure(L->DeductionFailure) <
9278 RankDeductionFailure(R->DeductionFailure);
9279
9280 // Sort everything else by location.
9281 SourceLocation LLoc = GetLocationForCandidate(L);
9282 SourceLocation RLoc = GetLocationForCandidate(R);
9283
9284 // Put candidates without locations (e.g. builtins) at the end.
9285 if (LLoc.isInvalid())
9286 return false;
9287 if (RLoc.isInvalid())
9288 return true;
9289
9290 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9291 }
9292};
9293
9294/// Diagnose a template argument deduction failure.
9295/// We are treating these failures as overload failures due to bad
9296/// deductions.
9297void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9298 DiagnoseBadDeduction(S, Specialization, // pattern
9299 DeductionFailure, /*NumArgs=*/0);
9300}
9301
9302void TemplateSpecCandidateSet::destroyCandidates() {
9303 for (iterator i = begin(), e = end(); i != e; ++i) {
9304 i->DeductionFailure.Destroy();
9305 }
9306}
9307
9308void TemplateSpecCandidateSet::clear() {
9309 destroyCandidates();
9310 Candidates.clear();
9311}
9312
9313/// NoteCandidates - When no template specialization match is found, prints
9314/// diagnostic messages containing the non-matching specializations that form
9315/// the candidate set.
9316/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9317/// OCD == OCD_AllCandidates and Cand->Viable == false.
9318void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9319 // Sort the candidates by position (assuming no candidate is a match).
9320 // Sorting directly would be prohibitive, so we make a set of pointers
9321 // and sort those.
9322 SmallVector<TemplateSpecCandidate *, 32> Cands;
9323 Cands.reserve(size());
9324 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9325 if (Cand->Specialization)
9326 Cands.push_back(Cand);
9327 // Otherwise, this is a non matching builtin candidate. We do not,
9328 // in general, want to list every possible builtin candidate.
9329 }
9330
9331 std::sort(Cands.begin(), Cands.end(),
9332 CompareTemplateSpecCandidatesForDisplay(S));
9333
9334 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9335 // for generalization purposes (?).
9336 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9337
9338 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9339 unsigned CandsShown = 0;
9340 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9341 TemplateSpecCandidate *Cand = *I;
9342
9343 // Set an arbitrary limit on the number of candidates we'll spam
9344 // the user with. FIXME: This limit should depend on details of the
9345 // candidate list.
9346 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9347 break;
9348 ++CandsShown;
9349
9350 assert(Cand->Specialization &&
9351 "Non-matching built-in candidates are not added to Cands.");
9352 Cand->NoteDeductionFailure(S);
9353 }
9354
9355 if (I != E)
9356 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9357}
9358
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009359// [PossiblyAFunctionType] --> [Return]
9360// NonFunctionType --> NonFunctionType
9361// R (A) --> R(A)
9362// R (*)(A) --> R (A)
9363// R (&)(A) --> R (A)
9364// R (S::*)(A) --> R (A)
9365QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9366 QualType Ret = PossiblyAFunctionType;
9367 if (const PointerType *ToTypePtr =
9368 PossiblyAFunctionType->getAs<PointerType>())
9369 Ret = ToTypePtr->getPointeeType();
9370 else if (const ReferenceType *ToTypeRef =
9371 PossiblyAFunctionType->getAs<ReferenceType>())
9372 Ret = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00009373 else if (const MemberPointerType *MemTypePtr =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009374 PossiblyAFunctionType->getAs<MemberPointerType>())
9375 Ret = MemTypePtr->getPointeeType();
9376 Ret =
9377 Context.getCanonicalType(Ret).getUnqualifiedType();
9378 return Ret;
9379}
Douglas Gregor904eed32008-11-10 20:40:00 +00009380
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009381// A helper class to help with address of function resolution
9382// - allows us to avoid passing around all those ugly parameters
9383class AddressOfFunctionResolver
9384{
9385 Sema& S;
9386 Expr* SourceExpr;
9387 const QualType& TargetType;
9388 QualType TargetFunctionType; // Extracted function type from target type
9389
9390 bool Complain;
9391 //DeclAccessPair& ResultFunctionAccessPair;
9392 ASTContext& Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009393
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009394 bool TargetTypeIsNonStaticMemberFunction;
9395 bool FoundNonTemplateFunction;
David Majnemer576a9af2013-08-01 06:13:59 +00009396 bool StaticMemberFunctionFromBoundPointer;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009397
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009398 OverloadExpr::FindResult OvlExprInfo;
9399 OverloadExpr *OvlExpr;
9400 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009401 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo43847122013-07-19 23:00:19 +00009402 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009403
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009404public:
Larisse Voufo43847122013-07-19 23:00:19 +00009405 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9406 const QualType &TargetType, bool Complain)
9407 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9408 Complain(Complain), Context(S.getASTContext()),
9409 TargetTypeIsNonStaticMemberFunction(
9410 !!TargetType->getAs<MemberPointerType>()),
9411 FoundNonTemplateFunction(false),
David Majnemer576a9af2013-08-01 06:13:59 +00009412 StaticMemberFunctionFromBoundPointer(false),
Larisse Voufo43847122013-07-19 23:00:19 +00009413 OvlExprInfo(OverloadExpr::find(SourceExpr)),
9414 OvlExpr(OvlExprInfo.Expression),
9415 FailedCandidates(OvlExpr->getNameLoc()) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009416 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruth90434232011-03-29 08:08:18 +00009417
David Majnemer576a9af2013-08-01 06:13:59 +00009418 if (TargetFunctionType->isFunctionType()) {
9419 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9420 if (!UME->isImplicitAccess() &&
9421 !S.ResolveSingleFunctionTemplateSpecialization(UME))
9422 StaticMemberFunctionFromBoundPointer = true;
9423 } else if (OvlExpr->hasExplicitTemplateArgs()) {
9424 DeclAccessPair dap;
9425 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9426 OvlExpr, false, &dap)) {
9427 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9428 if (!Method->isStatic()) {
9429 // If the target type is a non-function type and the function found
9430 // is a non-static member function, pretend as if that was the
9431 // target, it's the only possible type to end up with.
9432 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruth90434232011-03-29 08:08:18 +00009433
David Majnemer576a9af2013-08-01 06:13:59 +00009434 // And skip adding the function if its not in the proper form.
9435 // We'll diagnose this due to an empty set of functions.
9436 if (!OvlExprInfo.HasFormOfMemberPointer)
9437 return;
Chandler Carruth90434232011-03-29 08:08:18 +00009438 }
9439
David Majnemer576a9af2013-08-01 06:13:59 +00009440 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor83314aa2009-07-08 20:55:45 +00009441 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009442 return;
Douglas Gregor83314aa2009-07-08 20:55:45 +00009443 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009444
9445 if (OvlExpr->hasExplicitTemplateArgs())
9446 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00009447
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009448 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9449 // C++ [over.over]p4:
9450 // If more than one function is selected, [...]
9451 if (Matches.size() > 1) {
9452 if (FoundNonTemplateFunction)
9453 EliminateAllTemplateMatches();
9454 else
9455 EliminateAllExceptMostSpecializedTemplate();
9456 }
9457 }
9458 }
9459
9460private:
9461 bool isTargetTypeAFunction() const {
9462 return TargetFunctionType->isFunctionType();
9463 }
9464
9465 // [ToType] [Return]
9466
9467 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9468 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9469 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9470 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9471 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9472 }
9473
9474 // return true if any matching specializations were found
9475 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9476 const DeclAccessPair& CurAccessFunPair) {
9477 if (CXXMethodDecl *Method
9478 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9479 // Skip non-static function templates when converting to pointer, and
9480 // static when converting to member pointer.
9481 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9482 return false;
9483 }
9484 else if (TargetTypeIsNonStaticMemberFunction)
9485 return false;
9486
9487 // C++ [over.over]p2:
9488 // If the name is a function template, template argument deduction is
9489 // done (14.8.2.2), and if the argument deduction succeeds, the
9490 // resulting template argument list is used to generate a single
9491 // function template specialization, which is added to the set of
9492 // overloaded functions considered.
9493 FunctionDecl *Specialization = 0;
Larisse Voufo43847122013-07-19 23:00:19 +00009494 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009495 if (Sema::TemplateDeductionResult Result
9496 = S.DeduceTemplateArguments(FunctionTemplate,
9497 &OvlExplicitTemplateArgs,
9498 TargetFunctionType, Specialization,
Douglas Gregor092140a2013-04-17 08:45:07 +00009499 Info, /*InOverloadResolution=*/true)) {
Larisse Voufo43847122013-07-19 23:00:19 +00009500 // Make a note of the failed deduction for diagnostics.
9501 FailedCandidates.addCandidate()
9502 .set(FunctionTemplate->getTemplatedDecl(),
9503 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009504 return false;
9505 }
9506
Douglas Gregor092140a2013-04-17 08:45:07 +00009507 // Template argument deduction ensures that we have an exact match or
9508 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009509 // This function template specicalization works.
9510 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Douglas Gregor092140a2013-04-17 08:45:07 +00009511 assert(S.isSameOrCompatibleFunctionType(
9512 Context.getCanonicalType(Specialization->getType()),
9513 Context.getCanonicalType(TargetFunctionType)));
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009514 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9515 return true;
9516 }
9517
9518 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9519 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthbd647292009-12-29 06:17:27 +00009520 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00009521 // Skip non-static functions when converting to pointer, and static
9522 // when converting to member pointer.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009523 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9524 return false;
9525 }
9526 else if (TargetTypeIsNonStaticMemberFunction)
9527 return false;
Douglas Gregor904eed32008-11-10 20:40:00 +00009528
Chandler Carruthbd647292009-12-29 06:17:27 +00009529 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009530 if (S.getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00009531 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9532 if (S.CheckCUDATarget(Caller, FunDecl))
9533 return false;
9534
Richard Smith60e141e2013-05-04 07:00:32 +00009535 // If any candidate has a placeholder return type, trigger its deduction
9536 // now.
9537 if (S.getLangOpts().CPlusPlus1y &&
9538 FunDecl->getResultType()->isUndeducedType() &&
9539 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
9540 return false;
9541
Douglas Gregor43c79c22009-12-09 00:47:37 +00009542 QualType ResultTy;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009543 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9544 FunDecl->getType()) ||
Chandler Carruth18e04612011-06-18 01:19:03 +00009545 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9546 ResultTy)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009547 Matches.push_back(std::make_pair(CurAccessFunPair,
9548 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00009549 FoundNonTemplateFunction = true;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009550 return true;
Douglas Gregor00aeb522009-07-08 23:33:52 +00009551 }
Mike Stump1eb44332009-09-09 15:08:12 +00009552 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009553
9554 return false;
9555 }
9556
9557 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9558 bool Ret = false;
9559
9560 // If the overload expression doesn't have the form of a pointer to
9561 // member, don't try to convert it to a pointer-to-member type.
9562 if (IsInvalidFormOfPointerToMemberFunction())
9563 return false;
9564
9565 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9566 E = OvlExpr->decls_end();
9567 I != E; ++I) {
9568 // Look through any using declarations to find the underlying function.
9569 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9570
9571 // C++ [over.over]p3:
9572 // Non-member functions and static member functions match
9573 // targets of type "pointer-to-function" or "reference-to-function."
9574 // Nonstatic member functions match targets of
9575 // type "pointer-to-member-function."
9576 // Note that according to DR 247, the containing class does not matter.
9577 if (FunctionTemplateDecl *FunctionTemplate
9578 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9579 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9580 Ret = true;
9581 }
9582 // If we have explicit template arguments supplied, skip non-templates.
9583 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9584 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9585 Ret = true;
9586 }
9587 assert(Ret || Matches.empty());
9588 return Ret;
Douglas Gregor904eed32008-11-10 20:40:00 +00009589 }
9590
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009591 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00009592 // [...] and any given function template specialization F1 is
9593 // eliminated if the set contains a second function template
9594 // specialization whose function template is more specialized
9595 // than the function template of F1 according to the partial
9596 // ordering rules of 14.5.5.2.
9597
9598 // The algorithm specified above is quadratic. We instead use a
9599 // two-pass algorithm (similar to the one used to identify the
9600 // best viable function in an overload set) that identifies the
9601 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00009602
9603 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9604 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9605 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009606
Larisse Voufo43847122013-07-19 23:00:19 +00009607 // TODO: It looks like FailedCandidates does not serve much purpose
9608 // here, since the no_viable diagnostic has index 0.
9609 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith4ad09e62013-09-10 22:59:25 +00009610 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo43847122013-07-19 23:00:19 +00009611 SourceExpr->getLocStart(), S.PDiag(),
9612 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
9613 .second->getDeclName(),
9614 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
9615 Complain, TargetFunctionType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009616
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009617 if (Result != MatchesCopy.end()) {
9618 // Make it the first and only element
9619 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9620 Matches[0].second = cast<FunctionDecl>(*Result);
9621 Matches.resize(1);
John McCallc373d482010-01-27 01:50:18 +00009622 }
9623 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009624
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009625 void EliminateAllTemplateMatches() {
9626 // [...] any function template specializations in the set are
9627 // eliminated if the set also contains a non-template function, [...]
9628 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9629 if (Matches[I].second->getPrimaryTemplate() == 0)
9630 ++I;
9631 else {
9632 Matches[I] = Matches[--N];
9633 Matches.set_size(N);
9634 }
9635 }
9636 }
9637
9638public:
9639 void ComplainNoMatchesFound() const {
9640 assert(Matches.empty());
9641 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9642 << OvlExpr->getName() << TargetFunctionType
9643 << OvlExpr->getSourceRange();
Richard Smith72a36a12013-08-14 00:00:44 +00009644 if (FailedCandidates.empty())
9645 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9646 else {
9647 // We have some deduction failure messages. Use them to diagnose
9648 // the function templates, and diagnose the non-template candidates
9649 // normally.
9650 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9651 IEnd = OvlExpr->decls_end();
9652 I != IEnd; ++I)
9653 if (FunctionDecl *Fun =
9654 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
9655 S.NoteOverloadCandidate(Fun, TargetFunctionType);
9656 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
9657 }
9658 }
9659
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009660 bool IsInvalidFormOfPointerToMemberFunction() const {
9661 return TargetTypeIsNonStaticMemberFunction &&
9662 !OvlExprInfo.HasFormOfMemberPointer;
9663 }
David Majnemer576a9af2013-08-01 06:13:59 +00009664
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009665 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9666 // TODO: Should we condition this on whether any functions might
9667 // have matched, or is it more appropriate to do that in callers?
9668 // TODO: a fixit wouldn't hurt.
9669 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9670 << TargetType << OvlExpr->getSourceRange();
9671 }
David Majnemer576a9af2013-08-01 06:13:59 +00009672
9673 bool IsStaticMemberFunctionFromBoundPointer() const {
9674 return StaticMemberFunctionFromBoundPointer;
9675 }
9676
9677 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
9678 S.Diag(OvlExpr->getLocStart(),
9679 diag::err_invalid_form_pointer_member_function)
9680 << OvlExpr->getSourceRange();
9681 }
9682
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009683 void ComplainOfInvalidConversion() const {
9684 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9685 << OvlExpr->getName() << TargetType;
9686 }
9687
9688 void ComplainMultipleMatchesFound() const {
9689 assert(Matches.size() > 1);
9690 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9691 << OvlExpr->getName()
9692 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009693 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009694 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009695
9696 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9697
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009698 int getNumMatches() const { return Matches.size(); }
9699
9700 FunctionDecl* getMatchingFunctionDecl() const {
9701 if (Matches.size() != 1) return 0;
9702 return Matches[0].second;
9703 }
9704
9705 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9706 if (Matches.size() != 1) return 0;
9707 return &Matches[0].first;
9708 }
9709};
9710
9711/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9712/// an overloaded function (C++ [over.over]), where @p From is an
9713/// expression with overloaded function type and @p ToType is the type
9714/// we're trying to resolve to. For example:
9715///
9716/// @code
9717/// int f(double);
9718/// int f(int);
9719///
9720/// int (*pfd)(double) = f; // selects f(double)
9721/// @endcode
9722///
9723/// This routine returns the resulting FunctionDecl if it could be
9724/// resolved, and NULL otherwise. When @p Complain is true, this
9725/// routine will emit diagnostics if there is an error.
9726FunctionDecl *
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009727Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9728 QualType TargetType,
9729 bool Complain,
9730 DeclAccessPair &FoundResult,
9731 bool *pHadMultipleCandidates) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009732 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009733
9734 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9735 Complain);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009736 int NumMatches = Resolver.getNumMatches();
9737 FunctionDecl* Fn = 0;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009738 if (NumMatches == 0 && Complain) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009739 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9740 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9741 else
9742 Resolver.ComplainNoMatchesFound();
9743 }
9744 else if (NumMatches > 1 && Complain)
9745 Resolver.ComplainMultipleMatchesFound();
9746 else if (NumMatches == 1) {
9747 Fn = Resolver.getMatchingFunctionDecl();
9748 assert(Fn);
9749 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemer576a9af2013-08-01 06:13:59 +00009750 if (Complain) {
9751 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
9752 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
9753 else
9754 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
9755 }
Sebastian Redl07ab2022009-10-17 21:12:09 +00009756 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009757
9758 if (pHadMultipleCandidates)
9759 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009760 return Fn;
Douglas Gregor904eed32008-11-10 20:40:00 +00009761}
9762
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009763/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor4b52e252009-12-21 23:17:24 +00009764/// resolve that overloaded function expression down to a single function.
9765///
9766/// This routine can only resolve template-ids that refer to a single function
9767/// template, where that template-id refers to a single template whose template
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009768/// arguments are either provided by the template-id or have defaults,
Douglas Gregor4b52e252009-12-21 23:17:24 +00009769/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker8b407722013-10-20 18:48:56 +00009770///
9771/// If no template-ids are found, no diagnostics are emitted and NULL is
9772/// returned.
John McCall864c0412011-04-26 20:42:42 +00009773FunctionDecl *
9774Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9775 bool Complain,
9776 DeclAccessPair *FoundResult) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009777 // C++ [over.over]p1:
9778 // [...] [Note: any redundant set of parentheses surrounding the
9779 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00009780 // C++ [over.over]p1:
9781 // [...] The overloaded function name can be preceded by the &
9782 // operator.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009783
Douglas Gregor4b52e252009-12-21 23:17:24 +00009784 // If we didn't actually find any template-ids, we're done.
John McCall864c0412011-04-26 20:42:42 +00009785 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00009786 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00009787
9788 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall864c0412011-04-26 20:42:42 +00009789 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Larisse Voufo43847122013-07-19 23:00:19 +00009790 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009791
Douglas Gregor4b52e252009-12-21 23:17:24 +00009792 // Look through all of the overloaded functions, searching for one
9793 // whose type matches exactly.
9794 FunctionDecl *Matched = 0;
John McCall864c0412011-04-26 20:42:42 +00009795 for (UnresolvedSetIterator I = ovl->decls_begin(),
9796 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009797 // C++0x [temp.arg.explicit]p3:
9798 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009799 // where deduction is not done, if a template argument list is
9800 // specified and it, along with any default template arguments,
9801 // identifies a single function template specialization, then the
Douglas Gregor4b52e252009-12-21 23:17:24 +00009802 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00009803 FunctionTemplateDecl *FunctionTemplate
9804 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009805
Douglas Gregor4b52e252009-12-21 23:17:24 +00009806 // C++ [over.over]p2:
9807 // If the name is a function template, template argument deduction is
9808 // done (14.8.2.2), and if the argument deduction succeeds, the
9809 // resulting template argument list is used to generate a single
9810 // function template specialization, which is added to the set of
9811 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00009812 FunctionDecl *Specialization = 0;
Larisse Voufo43847122013-07-19 23:00:19 +00009813 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor4b52e252009-12-21 23:17:24 +00009814 if (TemplateDeductionResult Result
9815 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor092140a2013-04-17 08:45:07 +00009816 Specialization, Info,
9817 /*InOverloadResolution=*/true)) {
Larisse Voufo43847122013-07-19 23:00:19 +00009818 // Make a note of the failed deduction for diagnostics.
9819 // TODO: Actually use the failed-deduction info?
9820 FailedCandidates.addCandidate()
9821 .set(FunctionTemplate->getTemplatedDecl(),
9822 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor4b52e252009-12-21 23:17:24 +00009823 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009824 }
9825
John McCall864c0412011-04-26 20:42:42 +00009826 assert(Specialization && "no specialization and no error?");
9827
Douglas Gregor4b52e252009-12-21 23:17:24 +00009828 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009829 if (Matched) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009830 if (Complain) {
John McCall864c0412011-04-26 20:42:42 +00009831 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9832 << ovl->getName();
9833 NoteAllOverloadCandidates(ovl);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009834 }
Douglas Gregor4b52e252009-12-21 23:17:24 +00009835 return 0;
John McCall864c0412011-04-26 20:42:42 +00009836 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009837
John McCall864c0412011-04-26 20:42:42 +00009838 Matched = Specialization;
9839 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor4b52e252009-12-21 23:17:24 +00009840 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009841
Richard Smith60e141e2013-05-04 07:00:32 +00009842 if (Matched && getLangOpts().CPlusPlus1y &&
9843 Matched->getResultType()->isUndeducedType() &&
9844 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
9845 return 0;
9846
Douglas Gregor4b52e252009-12-21 23:17:24 +00009847 return Matched;
9848}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009849
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009850
9851
9852
John McCall6dbba4f2011-10-11 23:14:30 +00009853// Resolve and fix an overloaded expression that can be resolved
9854// because it identifies a single function template specialization.
9855//
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009856// Last three arguments should only be supplied if Complain = true
John McCall6dbba4f2011-10-11 23:14:30 +00009857//
9858// Return true if it was logically possible to so resolve the
9859// expression, regardless of whether or not it succeeded. Always
9860// returns true if 'complain' is set.
9861bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9862 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9863 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009864 QualType DestTypeForComplaining,
John McCall864c0412011-04-26 20:42:42 +00009865 unsigned DiagIDForComplaining) {
John McCall6dbba4f2011-10-11 23:14:30 +00009866 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009867
John McCall6dbba4f2011-10-11 23:14:30 +00009868 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009869
John McCall864c0412011-04-26 20:42:42 +00009870 DeclAccessPair found;
9871 ExprResult SingleFunctionExpression;
9872 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9873 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009874 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall6dbba4f2011-10-11 23:14:30 +00009875 SrcExpr = ExprError();
9876 return true;
9877 }
John McCall864c0412011-04-26 20:42:42 +00009878
9879 // It is only correct to resolve to an instance method if we're
9880 // resolving a form that's permitted to be a pointer to member.
9881 // Otherwise we'll end up making a bound member expression, which
9882 // is illegal in all the contexts we resolve like this.
9883 if (!ovl.HasFormOfMemberPointer &&
9884 isa<CXXMethodDecl>(fn) &&
9885 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall6dbba4f2011-10-11 23:14:30 +00009886 if (!complain) return false;
9887
9888 Diag(ovl.Expression->getExprLoc(),
9889 diag::err_bound_member_function)
9890 << 0 << ovl.Expression->getSourceRange();
9891
9892 // TODO: I believe we only end up here if there's a mix of
9893 // static and non-static candidates (otherwise the expression
9894 // would have 'bound member' type, not 'overload' type).
9895 // Ideally we would note which candidate was chosen and why
9896 // the static candidates were rejected.
9897 SrcExpr = ExprError();
9898 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009899 }
Douglas Gregordb2eae62011-03-16 19:16:25 +00009900
Sylvestre Ledru43e3dee2012-07-31 06:56:50 +00009901 // Fix the expression to refer to 'fn'.
John McCall864c0412011-04-26 20:42:42 +00009902 SingleFunctionExpression =
John McCall6dbba4f2011-10-11 23:14:30 +00009903 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall864c0412011-04-26 20:42:42 +00009904
9905 // If desired, do function-to-pointer decay.
John McCall6dbba4f2011-10-11 23:14:30 +00009906 if (doFunctionPointerConverion) {
John McCall864c0412011-04-26 20:42:42 +00009907 SingleFunctionExpression =
9908 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall6dbba4f2011-10-11 23:14:30 +00009909 if (SingleFunctionExpression.isInvalid()) {
9910 SrcExpr = ExprError();
9911 return true;
9912 }
9913 }
John McCall864c0412011-04-26 20:42:42 +00009914 }
9915
9916 if (!SingleFunctionExpression.isUsable()) {
9917 if (complain) {
9918 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9919 << ovl.Expression->getName()
9920 << DestTypeForComplaining
9921 << OpRangeForComplaining
9922 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall6dbba4f2011-10-11 23:14:30 +00009923 NoteAllOverloadCandidates(SrcExpr.get());
9924
9925 SrcExpr = ExprError();
9926 return true;
9927 }
9928
9929 return false;
John McCall864c0412011-04-26 20:42:42 +00009930 }
9931
John McCall6dbba4f2011-10-11 23:14:30 +00009932 SrcExpr = SingleFunctionExpression;
9933 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009934}
9935
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009936/// \brief Add a single candidate to the overload set.
9937static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00009938 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00009939 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009940 ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009941 OverloadCandidateSet &CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00009942 bool PartialOverloading,
9943 bool KnownValid) {
John McCall9aa472c2010-03-19 07:35:19 +00009944 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00009945 if (isa<UsingShadowDecl>(Callee))
9946 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9947
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009948 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith2ced0442011-06-26 22:19:54 +00009949 if (ExplicitTemplateArgs) {
9950 assert(!KnownValid && "Explicit template arguments?");
9951 return;
9952 }
Ahmed Charles13a140c2012-02-25 11:00:22 +00009953 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9954 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009955 return;
John McCallba135432009-11-21 08:51:07 +00009956 }
9957
9958 if (FunctionTemplateDecl *FuncTemplate
9959 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00009960 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009961 ExplicitTemplateArgs, Args, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00009962 return;
9963 }
9964
Richard Smith2ced0442011-06-26 22:19:54 +00009965 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009966}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009967
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009968/// \brief Add the overload candidates named by callee and/or found by argument
9969/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00009970void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009971 ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009972 OverloadCandidateSet &CandidateSet,
9973 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00009974
9975#ifndef NDEBUG
9976 // Verify that ArgumentDependentLookup is consistent with the rules
9977 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009978 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009979 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9980 // and let Y be the lookup set produced by argument dependent
9981 // lookup (defined as follows). If X contains
9982 //
9983 // -- a declaration of a class member, or
9984 //
9985 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00009986 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009987 //
9988 // -- a declaration that is neither a function or a function
9989 // template
9990 //
9991 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00009992
John McCall3b4294e2009-12-16 12:17:52 +00009993 if (ULE->requiresADL()) {
9994 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9995 E = ULE->decls_end(); I != E; ++I) {
9996 assert(!(*I)->getDeclContext()->isRecord());
9997 assert(isa<UsingShadowDecl>(*I) ||
9998 !(*I)->getDeclContext()->isFunctionOrMethod());
9999 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +000010000 }
10001 }
10002#endif
10003
John McCall3b4294e2009-12-16 12:17:52 +000010004 // It would be nice to avoid this copy.
10005 TemplateArgumentListInfo TABuffer;
Douglas Gregor67714232011-03-03 02:41:12 +000010006 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +000010007 if (ULE->hasExplicitTemplateArgs()) {
10008 ULE->copyTemplateArgumentsInto(TABuffer);
10009 ExplicitTemplateArgs = &TABuffer;
10010 }
10011
10012 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10013 E = ULE->decls_end(); I != E; ++I)
Ahmed Charles13a140c2012-02-25 11:00:22 +000010014 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10015 CandidateSet, PartialOverloading,
10016 /*KnownValid*/ true);
John McCallba135432009-11-21 08:51:07 +000010017
John McCall3b4294e2009-12-16 12:17:52 +000010018 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +000010019 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithf5cd5cc2012-02-25 06:24:24 +000010020 ULE->getExprLoc(),
Ahmed Charles13a140c2012-02-25 11:00:22 +000010021 Args, ExplicitTemplateArgs,
Richard Smithb1502bc2012-10-18 17:56:02 +000010022 CandidateSet, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +000010023}
John McCall578b69b2009-12-16 08:11:27 +000010024
Richard Smithd3ff3252013-06-12 22:56:54 +000010025/// Determine whether a declaration with the specified name could be moved into
10026/// a different namespace.
10027static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10028 switch (Name.getCXXOverloadedOperator()) {
10029 case OO_New: case OO_Array_New:
10030 case OO_Delete: case OO_Array_Delete:
10031 return false;
10032
10033 default:
10034 return true;
10035 }
10036}
10037
Richard Smithf50e88a2011-06-05 22:42:48 +000010038/// Attempt to recover from an ill-formed use of a non-dependent name in a
10039/// template, where the non-dependent name was declared after the template
10040/// was defined. This is common in code written for a compilers which do not
10041/// correctly implement two-stage name lookup.
10042///
10043/// Returns true if a viable candidate was found and a diagnostic was issued.
10044static bool
10045DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10046 const CXXScopeSpec &SS, LookupResult &R,
10047 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010048 ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +000010049 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10050 return false;
10051
10052 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewycky5a7120c2012-03-14 20:41:00 +000010053 if (DC->isTransparentContext())
10054 continue;
10055
Richard Smithf50e88a2011-06-05 22:42:48 +000010056 SemaRef.LookupQualifiedName(R, DC);
10057
10058 if (!R.empty()) {
10059 R.suppressDiagnostics();
10060
10061 if (isa<CXXRecordDecl>(DC)) {
10062 // Don't diagnose names we find in classes; we get much better
10063 // diagnostics for these from DiagnoseEmptyLookup.
10064 R.clear();
10065 return false;
10066 }
10067
10068 OverloadCandidateSet Candidates(FnLoc);
10069 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10070 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charles13a140c2012-02-25 11:00:22 +000010071 ExplicitTemplateArgs, Args,
Richard Smith2ced0442011-06-26 22:19:54 +000010072 Candidates, false, /*KnownValid*/ false);
Richard Smithf50e88a2011-06-05 22:42:48 +000010073
10074 OverloadCandidateSet::iterator Best;
Richard Smith2ced0442011-06-26 22:19:54 +000010075 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smithf50e88a2011-06-05 22:42:48 +000010076 // No viable functions. Don't bother the user with notes for functions
10077 // which don't work and shouldn't be found anyway.
Richard Smith2ced0442011-06-26 22:19:54 +000010078 R.clear();
Richard Smithf50e88a2011-06-05 22:42:48 +000010079 return false;
Richard Smith2ced0442011-06-26 22:19:54 +000010080 }
Richard Smithf50e88a2011-06-05 22:42:48 +000010081
10082 // Find the namespaces where ADL would have looked, and suggest
10083 // declaring the function there instead.
10084 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10085 Sema::AssociatedClassSet AssociatedClasses;
John McCall42f48fb2012-08-24 20:38:34 +000010086 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smithf50e88a2011-06-05 22:42:48 +000010087 AssociatedNamespaces,
10088 AssociatedClasses);
Chandler Carruth74d487e2011-06-05 23:36:55 +000010089 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smithd3ff3252013-06-12 22:56:54 +000010090 if (canBeDeclaredInNamespace(R.getLookupName())) {
10091 DeclContext *Std = SemaRef.getStdNamespace();
10092 for (Sema::AssociatedNamespaceSet::iterator
10093 it = AssociatedNamespaces.begin(),
10094 end = AssociatedNamespaces.end(); it != end; ++it) {
10095 // Never suggest declaring a function within namespace 'std'.
10096 if (Std && Std->Encloses(*it))
10097 continue;
Richard Smith19e0d952012-12-22 02:46:14 +000010098
Richard Smithd3ff3252013-06-12 22:56:54 +000010099 // Never suggest declaring a function within a namespace with a
10100 // reserved name, like __gnu_cxx.
10101 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10102 if (NS &&
10103 NS->getQualifiedNameAsString().find("__") != std::string::npos)
10104 continue;
10105
10106 SuggestedNamespaces.insert(*it);
10107 }
Richard Smithf50e88a2011-06-05 22:42:48 +000010108 }
10109
10110 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10111 << R.getLookupName();
Chandler Carruth74d487e2011-06-05 23:36:55 +000010112 if (SuggestedNamespaces.empty()) {
Richard Smithf50e88a2011-06-05 22:42:48 +000010113 SemaRef.Diag(Best->Function->getLocation(),
10114 diag::note_not_found_by_two_phase_lookup)
10115 << R.getLookupName() << 0;
Chandler Carruth74d487e2011-06-05 23:36:55 +000010116 } else if (SuggestedNamespaces.size() == 1) {
Richard Smithf50e88a2011-06-05 22:42:48 +000010117 SemaRef.Diag(Best->Function->getLocation(),
10118 diag::note_not_found_by_two_phase_lookup)
Chandler Carruth74d487e2011-06-05 23:36:55 +000010119 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smithf50e88a2011-06-05 22:42:48 +000010120 } else {
10121 // FIXME: It would be useful to list the associated namespaces here,
10122 // but the diagnostics infrastructure doesn't provide a way to produce
10123 // a localized representation of a list of items.
10124 SemaRef.Diag(Best->Function->getLocation(),
10125 diag::note_not_found_by_two_phase_lookup)
10126 << R.getLookupName() << 2;
10127 }
10128
10129 // Try to recover by calling this function.
10130 return true;
10131 }
10132
10133 R.clear();
10134 }
10135
10136 return false;
10137}
10138
10139/// Attempt to recover from ill-formed use of a non-dependent operator in a
10140/// template, where the non-dependent operator was declared after the template
10141/// was defined.
10142///
10143/// Returns true if a viable candidate was found and a diagnostic was issued.
10144static bool
10145DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10146 SourceLocation OpLoc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010147 ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +000010148 DeclarationName OpName =
10149 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10150 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10151 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010152 /*ExplicitTemplateArgs=*/0, Args);
Richard Smithf50e88a2011-06-05 22:42:48 +000010153}
10154
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +000010155namespace {
Richard Smithe49ff3e2012-09-25 04:46:05 +000010156class BuildRecoveryCallExprRAII {
10157 Sema &SemaRef;
10158public:
10159 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10160 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10161 SemaRef.IsBuildingRecoveryCallExpr = true;
10162 }
10163
10164 ~BuildRecoveryCallExprRAII() {
10165 SemaRef.IsBuildingRecoveryCallExpr = false;
10166 }
10167};
10168
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +000010169}
10170
John McCall578b69b2009-12-16 08:11:27 +000010171/// Attempts to recover from a call where no functions were found.
10172///
10173/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +000010174static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +000010175BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +000010176 UnresolvedLookupExpr *ULE,
10177 SourceLocation LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010178 llvm::MutableArrayRef<Expr *> Args,
Richard Smithf50e88a2011-06-05 22:42:48 +000010179 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +000010180 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smithe49ff3e2012-09-25 04:46:05 +000010181 // Do not try to recover if it is already building a recovery call.
10182 // This stops infinite loops for template instantiations like
10183 //
10184 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10185 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10186 //
10187 if (SemaRef.IsBuildingRecoveryCallExpr)
10188 return ExprError();
10189 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCall578b69b2009-12-16 08:11:27 +000010190
10191 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +000010192 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnarae4b92762012-01-27 09:46:47 +000010193 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCall578b69b2009-12-16 08:11:27 +000010194
John McCall3b4294e2009-12-16 12:17:52 +000010195 TemplateArgumentListInfo TABuffer;
Richard Smithf50e88a2011-06-05 22:42:48 +000010196 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +000010197 if (ULE->hasExplicitTemplateArgs()) {
10198 ULE->copyTemplateArgumentsInto(TABuffer);
10199 ExplicitTemplateArgs = &TABuffer;
10200 }
10201
John McCall578b69b2009-12-16 08:11:27 +000010202 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10203 Sema::LookupOrdinaryName);
Kaelyn Uhrain761695f2013-07-08 23:13:39 +000010204 FunctionCallFilterCCC Validator(SemaRef, Args.size(),
10205 ExplicitTemplateArgs != 0);
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +000010206 NoTypoCorrectionCCC RejectAll;
10207 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
10208 (CorrectionCandidateCallback*)&Validator :
10209 (CorrectionCandidateCallback*)&RejectAll;
Richard Smithf50e88a2011-06-05 22:42:48 +000010210 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010211 ExplicitTemplateArgs, Args) &&
Richard Smithf50e88a2011-06-05 22:42:48 +000010212 (!EmptyLookup ||
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +000010213 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010214 ExplicitTemplateArgs, Args)))
John McCallf312b1e2010-08-26 23:41:50 +000010215 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +000010216
John McCall3b4294e2009-12-16 12:17:52 +000010217 assert(!R.empty() && "lookup results empty despite recovery");
10218
10219 // Build an implicit member call if appropriate. Just drop the
10220 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +000010221 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +000010222 if ((*R.begin())->isCXXClassMember())
Abramo Bagnarae4b92762012-01-27 09:46:47 +000010223 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
10224 R, ExplicitTemplateArgs);
Abramo Bagnara9d9922a2012-02-06 14:31:00 +000010225 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnarae4b92762012-01-27 09:46:47 +000010226 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara9d9922a2012-02-06 14:31:00 +000010227 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +000010228 else
10229 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10230
10231 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +000010232 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +000010233
10234 // This shouldn't cause an infinite loop because we're giving it
Richard Smithf50e88a2011-06-05 22:42:48 +000010235 // an expression with viable lookup results, which should never
John McCall3b4294e2009-12-16 12:17:52 +000010236 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +000010237 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010238 MultiExprArg(Args.data(), Args.size()),
10239 RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +000010240}
Douglas Gregord7a95972010-06-08 17:35:15 +000010241
Sam Panzere1715b62012-08-21 00:52:01 +000010242/// \brief Constructs and populates an OverloadedCandidateSet from
10243/// the given function.
10244/// \returns true when an the ExprResult output parameter has been set.
10245bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10246 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010247 MultiExprArg Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010248 SourceLocation RParenLoc,
10249 OverloadCandidateSet *CandidateSet,
10250 ExprResult *Result) {
John McCall3b4294e2009-12-16 12:17:52 +000010251#ifndef NDEBUG
10252 if (ULE->requiresADL()) {
10253 // To do ADL, we must have found an unqualified name.
10254 assert(!ULE->getQualifier() && "qualified name with ADL");
10255
10256 // We don't perform ADL for implicit declarations of builtins.
10257 // Verify that this was correctly set up.
10258 FunctionDecl *F;
10259 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10260 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10261 F->getBuiltinID() && F->isImplicit())
David Blaikieb219cfc2011-09-23 05:06:16 +000010262 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010263
John McCall3b4294e2009-12-16 12:17:52 +000010264 // We don't perform ADL in C.
David Blaikie4e4d0842012-03-11 07:00:24 +000010265 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb1502bc2012-10-18 17:56:02 +000010266 }
John McCall3b4294e2009-12-16 12:17:52 +000010267#endif
10268
John McCall5acb0c92011-10-17 18:40:02 +000010269 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010270 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzere1715b62012-08-21 00:52:01 +000010271 *Result = ExprError();
10272 return true;
10273 }
Douglas Gregor17330012009-02-04 15:01:18 +000010274
John McCall3b4294e2009-12-16 12:17:52 +000010275 // Add the functions denoted by the callee to the set of candidate
10276 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010277 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +000010278
10279 // If we found nothing, try to recover.
Richard Smithf50e88a2011-06-05 22:42:48 +000010280 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
10281 // out if it fails.
Sam Panzere1715b62012-08-21 00:52:01 +000010282 if (CandidateSet->empty()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +000010283 // In Microsoft mode, if we are inside a template class member function then
10284 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichet0f74d1e2011-09-07 00:14:57 +000010285 // to instantiation time to be able to search into type dependent base
Sebastian Redl14b0c192011-09-24 17:48:00 +000010286 // classes.
David Blaikie4e4d0842012-03-11 07:00:24 +000010287 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetc8ff9152011-11-25 01:10:54 +000010288 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010289 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010290 Context.DependentTy, VK_RValue,
10291 RParenLoc);
Sebastian Redl14b0c192011-09-24 17:48:00 +000010292 CE->setTypeDependent(true);
Sam Panzere1715b62012-08-21 00:52:01 +000010293 *Result = Owned(CE);
10294 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +000010295 }
Sam Panzere1715b62012-08-21 00:52:01 +000010296 return false;
Francois Pichet0f74d1e2011-09-07 00:14:57 +000010297 }
John McCall578b69b2009-12-16 08:11:27 +000010298
John McCall5acb0c92011-10-17 18:40:02 +000010299 UnbridgedCasts.restore();
Sam Panzere1715b62012-08-21 00:52:01 +000010300 return false;
10301}
John McCall5acb0c92011-10-17 18:40:02 +000010302
Sam Panzere1715b62012-08-21 00:52:01 +000010303/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10304/// the completed call expression. If overload resolution fails, emits
10305/// diagnostics and returns ExprError()
10306static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10307 UnresolvedLookupExpr *ULE,
10308 SourceLocation LParenLoc,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010309 MultiExprArg Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010310 SourceLocation RParenLoc,
10311 Expr *ExecConfig,
10312 OverloadCandidateSet *CandidateSet,
10313 OverloadCandidateSet::iterator *Best,
10314 OverloadingResult OverloadResult,
10315 bool AllowTypoCorrection) {
10316 if (CandidateSet->empty())
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010317 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010318 RParenLoc, /*EmptyLookup=*/true,
10319 AllowTypoCorrection);
10320
10321 switch (OverloadResult) {
John McCall3b4294e2009-12-16 12:17:52 +000010322 case OR_Success: {
Sam Panzere1715b62012-08-21 00:52:01 +000010323 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzere1715b62012-08-21 00:52:01 +000010324 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +000010325 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10326 return ExprError();
Sam Panzere1715b62012-08-21 00:52:01 +000010327 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010328 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10329 ExecConfig);
John McCall3b4294e2009-12-16 12:17:52 +000010330 }
Douglas Gregorf6b89692008-11-26 05:54:23 +000010331
Richard Smithf50e88a2011-06-05 22:42:48 +000010332 case OR_No_Viable_Function: {
10333 // Try to recover by looking for viable functions which the user might
10334 // have meant to call.
Sam Panzere1715b62012-08-21 00:52:01 +000010335 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010336 Args, RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +000010337 /*EmptyLookup=*/false,
10338 AllowTypoCorrection);
Richard Smithf50e88a2011-06-05 22:42:48 +000010339 if (!Recovery.isInvalid())
10340 return Recovery;
10341
Sam Panzere1715b62012-08-21 00:52:01 +000010342 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregorf6b89692008-11-26 05:54:23 +000010343 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +000010344 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010345 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregorf6b89692008-11-26 05:54:23 +000010346 break;
Richard Smithf50e88a2011-06-05 22:42:48 +000010347 }
Douglas Gregorf6b89692008-11-26 05:54:23 +000010348
10349 case OR_Ambiguous:
Sam Panzere1715b62012-08-21 00:52:01 +000010350 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +000010351 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010352 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregorf6b89692008-11-26 05:54:23 +000010353 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010354
Sam Panzere1715b62012-08-21 00:52:01 +000010355 case OR_Deleted: {
10356 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10357 << (*Best)->Function->isDeleted()
10358 << ULE->getName()
10359 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10360 << Fn->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010361 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis0d579b62011-11-04 15:58:13 +000010362
Sam Panzere1715b62012-08-21 00:52:01 +000010363 // We emitted an error for the unvailable/deleted function call but keep
10364 // the call in the AST.
10365 FunctionDecl *FDecl = (*Best)->Function;
10366 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010367 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10368 ExecConfig);
Sam Panzere1715b62012-08-21 00:52:01 +000010369 }
Douglas Gregorf6b89692008-11-26 05:54:23 +000010370 }
10371
Douglas Gregorff331c12010-07-25 18:17:45 +000010372 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +000010373 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +000010374}
10375
Sam Panzere1715b62012-08-21 00:52:01 +000010376/// BuildOverloadedCallExpr - Given the call expression that calls Fn
10377/// (which eventually refers to the declaration Func) and the call
10378/// arguments Args/NumArgs, attempt to resolve the function call down
10379/// to a specific function. If overload resolution succeeds, returns
10380/// the call expression produced by overload resolution.
10381/// Otherwise, emits diagnostics and returns ExprError.
10382ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10383 UnresolvedLookupExpr *ULE,
10384 SourceLocation LParenLoc,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010385 MultiExprArg Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010386 SourceLocation RParenLoc,
10387 Expr *ExecConfig,
10388 bool AllowTypoCorrection) {
10389 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
10390 ExprResult result;
10391
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010392 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10393 &result))
Sam Panzere1715b62012-08-21 00:52:01 +000010394 return result;
10395
10396 OverloadCandidateSet::iterator Best;
10397 OverloadingResult OverloadResult =
10398 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10399
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010400 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010401 RParenLoc, ExecConfig, &CandidateSet,
10402 &Best, OverloadResult,
10403 AllowTypoCorrection);
10404}
10405
John McCall6e266892010-01-26 03:27:55 +000010406static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +000010407 return Functions.size() > 1 ||
10408 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10409}
10410
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010411/// \brief Create a unary operation that may resolve to an overloaded
10412/// operator.
10413///
10414/// \param OpLoc The location of the operator itself (e.g., '*').
10415///
10416/// \param OpcIn The UnaryOperator::Opcode that describes this
10417/// operator.
10418///
James Dennett40ae6662012-06-22 08:52:37 +000010419/// \param Fns The set of non-member functions that will be
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010420/// considered by overload resolution. The caller needs to build this
10421/// set based on the context using, e.g.,
10422/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10423/// set should not contain any member functions; those will be added
10424/// by CreateOverloadedUnaryOp().
10425///
James Dennett8da16872012-06-22 10:32:46 +000010426/// \param Input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010427ExprResult
John McCall6e266892010-01-26 03:27:55 +000010428Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10429 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +000010430 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010431 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010432
10433 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10434 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10435 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +000010436 // TODO: provide better source location info.
10437 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010438
John McCall5acb0c92011-10-17 18:40:02 +000010439 if (checkPlaceholderForOverload(*this, Input))
10440 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010441
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010442 Expr *Args[2] = { Input, 0 };
10443 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +000010444
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010445 // For post-increment and post-decrement, add the implicit '0' as
10446 // the second argument, so that we know this is a post-increment or
10447 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +000010448 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010449 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +000010450 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10451 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010452 NumArgs = 2;
10453 }
10454
Richard Smith958ba642013-05-05 15:51:06 +000010455 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10456
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010457 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010458 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +000010459 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010460 Opc,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010461 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010462 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010463 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010464
John McCallc373d482010-01-27 01:50:18 +000010465 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +000010466 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010467 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010468 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010469 /*ADL*/ true, IsOverloaded(Fns),
10470 Fns.begin(), Fns.end());
Richard Smith958ba642013-05-05 15:51:06 +000010471 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, ArgsArray,
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010472 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010473 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +000010474 OpLoc, false));
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010475 }
10476
10477 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010478 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010479
10480 // Add the candidates from the given function set.
Richard Smith958ba642013-05-05 15:51:06 +000010481 AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010482
10483 // Add operator candidates that are member functions.
Richard Smith958ba642013-05-05 15:51:06 +000010484 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010485
John McCall6e266892010-01-26 03:27:55 +000010486 // Add candidates from ADL.
Richard Smith958ba642013-05-05 15:51:06 +000010487 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, OpLoc,
10488 ArgsArray, /*ExplicitTemplateArgs*/ 0,
John McCall6e266892010-01-26 03:27:55 +000010489 CandidateSet);
10490
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010491 // Add builtin operator candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010492 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010493
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010494 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10495
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010496 // Perform overload resolution.
10497 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010498 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010499 case OR_Success: {
10500 // We found a built-in operator or an overloaded operator.
10501 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +000010502
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010503 if (FnDecl) {
10504 // We matched an overloaded operator. Build a call to that
10505 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +000010506
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010507 // Convert the arguments.
10508 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +000010509 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010510
John Wiegley429bb272011-04-08 18:41:53 +000010511 ExprResult InputRes =
10512 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10513 Best->FoundDecl, Method);
10514 if (InputRes.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010515 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010516 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010517 } else {
10518 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010519 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +000010520 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010521 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +000010522 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010523 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +000010524 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +000010525 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010526 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +000010527 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010528 }
10529
John McCallf89e55a2010-11-18 06:31:45 +000010530 // Determine the result type.
10531 QualType ResultTy = FnDecl->getResultType();
10532 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10533 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +000010534
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010535 // Build the actual expression node.
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010536 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010537 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010538 if (FnExpr.isInvalid())
10539 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +000010540
Eli Friedman4c3b8962009-11-18 03:58:17 +000010541 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +000010542 CallExpr *TheCall =
Richard Smith958ba642013-05-05 15:51:06 +000010543 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), ArgsArray,
Lang Hamesbe9af122012-10-02 04:45:10 +000010544 ResultTy, VK, OpLoc, false);
John McCallb697e082010-05-06 18:15:07 +000010545
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010546 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +000010547 FnDecl))
10548 return ExprError();
10549
John McCall9ae2f072010-08-23 23:25:46 +000010550 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010551 } else {
10552 // We matched a built-in operator. Convert the arguments, then
10553 // break out so that we will build the appropriate built-in
10554 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010555 ExprResult InputRes =
10556 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10557 Best->Conversions[0], AA_Passing);
10558 if (InputRes.isInvalid())
10559 return ExprError();
10560 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010561 break;
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010562 }
John Wiegley429bb272011-04-08 18:41:53 +000010563 }
10564
10565 case OR_No_Viable_Function:
Richard Smithf50e88a2011-06-05 22:42:48 +000010566 // This is an erroneous use of an operator which can be overloaded by
10567 // a non-member function. Check for non-member operators which were
10568 // defined too late to be candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010569 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smithf50e88a2011-06-05 22:42:48 +000010570 // FIXME: Recover by calling the found function.
10571 return ExprError();
10572
John Wiegley429bb272011-04-08 18:41:53 +000010573 // No viable function; fall through to handling this as a
10574 // built-in operator, which will produce an error message for us.
10575 break;
10576
10577 case OR_Ambiguous:
10578 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10579 << UnaryOperator::getOpcodeStr(Opc)
10580 << Input->getType()
10581 << Input->getSourceRange();
Richard Smith958ba642013-05-05 15:51:06 +000010582 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley429bb272011-04-08 18:41:53 +000010583 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10584 return ExprError();
10585
10586 case OR_Deleted:
10587 Diag(OpLoc, diag::err_ovl_deleted_oper)
10588 << Best->Function->isDeleted()
10589 << UnaryOperator::getOpcodeStr(Opc)
10590 << getDeletedOrUnavailableSuffix(Best->Function)
10591 << Input->getSourceRange();
Richard Smith958ba642013-05-05 15:51:06 +000010592 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman1795d372011-08-26 19:46:22 +000010593 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010594 return ExprError();
10595 }
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010596
10597 // Either we found no viable overloaded operator or we matched a
10598 // built-in operator. In either case, fall through to trying to
10599 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +000010600 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010601}
10602
Douglas Gregor063daf62009-03-13 18:40:31 +000010603/// \brief Create a binary operation that may resolve to an overloaded
10604/// operator.
10605///
10606/// \param OpLoc The location of the operator itself (e.g., '+').
10607///
10608/// \param OpcIn The BinaryOperator::Opcode that describes this
10609/// operator.
10610///
James Dennett40ae6662012-06-22 08:52:37 +000010611/// \param Fns The set of non-member functions that will be
Douglas Gregor063daf62009-03-13 18:40:31 +000010612/// considered by overload resolution. The caller needs to build this
10613/// set based on the context using, e.g.,
10614/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10615/// set should not contain any member functions; those will be added
10616/// by CreateOverloadedBinOp().
10617///
10618/// \param LHS Left-hand argument.
10619/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010620ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +000010621Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +000010622 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +000010623 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +000010624 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +000010625 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010626 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +000010627
10628 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10629 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10630 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10631
10632 // If either side is type-dependent, create an appropriate dependent
10633 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010634 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +000010635 if (Fns.empty()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010636 // If there are no functions to store, just build a dependent
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010637 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +000010638 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010639 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +000010640 Context.DependentTy,
10641 VK_RValue, OK_Ordinary,
Lang Hamesbe9af122012-10-02 04:45:10 +000010642 OpLoc,
10643 FPFeatures.fp_contract));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010644
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010645 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10646 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010647 VK_LValue,
10648 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010649 Context.DependentTy,
10650 Context.DependentTy,
Lang Hamesbe9af122012-10-02 04:45:10 +000010651 OpLoc,
10652 FPFeatures.fp_contract));
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010653 }
John McCall6e266892010-01-26 03:27:55 +000010654
10655 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +000010656 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010657 // TODO: provide better source location info in DNLoc component.
10658 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +000010659 UnresolvedLookupExpr *Fn
Douglas Gregor4c9be892011-02-28 20:01:57 +000010660 = UnresolvedLookupExpr::Create(Context, NamingClass,
10661 NestedNameSpecifierLoc(), OpNameInfo,
10662 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010663 Fns.begin(), Fns.end());
Lang Hamesbe9af122012-10-02 04:45:10 +000010664 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10665 Context.DependentTy, VK_RValue,
10666 OpLoc, FPFeatures.fp_contract));
Douglas Gregor063daf62009-03-13 18:40:31 +000010667 }
10668
John McCall5acb0c92011-10-17 18:40:02 +000010669 // Always do placeholder-like conversions on the RHS.
10670 if (checkPlaceholderForOverload(*this, Args[1]))
10671 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010672
John McCall3c3b7f92011-10-25 17:37:35 +000010673 // Do placeholder-like conversion on the LHS; note that we should
10674 // not get here with a PseudoObject LHS.
10675 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall5acb0c92011-10-17 18:40:02 +000010676 if (checkPlaceholderForOverload(*this, Args[0]))
10677 return ExprError();
10678
Sebastian Redl275c2b42009-11-18 23:10:33 +000010679 // If this is the assignment operator, we only perform overload resolution
10680 // if the left-hand side is a class or enumeration type. This is actually
10681 // a hack. The standard requires that we do overload resolution between the
10682 // various built-in candidates, but as DR507 points out, this can lead to
10683 // problems. So we do it this way, which pretty much follows what GCC does.
10684 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +000010685 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010686 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010687
John McCall0e800c92010-12-04 08:14:53 +000010688 // If this is the .* operator, which is not overloadable, just
10689 // create a built-in binary operator.
10690 if (Opc == BO_PtrMemD)
10691 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10692
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010693 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010694 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010695
10696 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010697 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +000010698
10699 // Add operator candidates that are member functions.
Richard Smith958ba642013-05-05 15:51:06 +000010700 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +000010701
John McCall6e266892010-01-26 03:27:55 +000010702 // Add candidates from ADL.
10703 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010704 OpLoc, Args,
John McCall6e266892010-01-26 03:27:55 +000010705 /*ExplicitTemplateArgs*/ 0,
10706 CandidateSet);
10707
Douglas Gregor063daf62009-03-13 18:40:31 +000010708 // Add builtin operator candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010709 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +000010710
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010711 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10712
Douglas Gregor063daf62009-03-13 18:40:31 +000010713 // Perform overload resolution.
10714 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010715 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +000010716 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +000010717 // We found a built-in operator or an overloaded operator.
10718 FunctionDecl *FnDecl = Best->Function;
10719
10720 if (FnDecl) {
10721 // We matched an overloaded operator. Build a call to that
10722 // operator.
10723
10724 // Convert the arguments.
10725 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +000010726 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +000010727 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010728
Chandler Carruth6df868e2010-12-12 08:17:55 +000010729 ExprResult Arg1 =
10730 PerformCopyInitialization(
10731 InitializedEntity::InitializeParameter(Context,
10732 FnDecl->getParamDecl(0)),
10733 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010734 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010735 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010736
John Wiegley429bb272011-04-08 18:41:53 +000010737 ExprResult Arg0 =
10738 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10739 Best->FoundDecl, Method);
10740 if (Arg0.isInvalid())
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010741 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010742 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010743 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010744 } else {
10745 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +000010746 ExprResult Arg0 = PerformCopyInitialization(
10747 InitializedEntity::InitializeParameter(Context,
10748 FnDecl->getParamDecl(0)),
10749 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010750 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010751 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010752
Chandler Carruth6df868e2010-12-12 08:17:55 +000010753 ExprResult Arg1 =
10754 PerformCopyInitialization(
10755 InitializedEntity::InitializeParameter(Context,
10756 FnDecl->getParamDecl(1)),
10757 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010758 if (Arg1.isInvalid())
10759 return ExprError();
10760 Args[0] = LHS = Arg0.takeAs<Expr>();
10761 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010762 }
10763
John McCallf89e55a2010-11-18 06:31:45 +000010764 // Determine the result type.
10765 QualType ResultTy = FnDecl->getResultType();
10766 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10767 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +000010768
10769 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010770 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010771 Best->FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010772 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010773 if (FnExpr.isInvalid())
10774 return ExprError();
Douglas Gregor063daf62009-03-13 18:40:31 +000010775
John McCall9ae2f072010-08-23 23:25:46 +000010776 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010777 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000010778 Args, ResultTy, VK, OpLoc,
10779 FPFeatures.fp_contract);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010780
10781 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000010782 FnDecl))
10783 return ExprError();
10784
Nick Lewycky9b7ea0d2013-01-24 02:03:08 +000010785 ArrayRef<const Expr *> ArgsArray(Args, 2);
10786 // Cut off the implicit 'this'.
10787 if (isa<CXXMethodDecl>(FnDecl))
10788 ArgsArray = ArgsArray.slice(1);
10789 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
10790 TheCall->getSourceRange(), VariadicDoesNotApply);
10791
John McCall9ae2f072010-08-23 23:25:46 +000010792 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +000010793 } else {
10794 // We matched a built-in operator. Convert the arguments, then
10795 // break out so that we will build the appropriate built-in
10796 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010797 ExprResult ArgsRes0 =
10798 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10799 Best->Conversions[0], AA_Passing);
10800 if (ArgsRes0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010801 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010802 Args[0] = ArgsRes0.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010803
John Wiegley429bb272011-04-08 18:41:53 +000010804 ExprResult ArgsRes1 =
10805 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10806 Best->Conversions[1], AA_Passing);
10807 if (ArgsRes1.isInvalid())
10808 return ExprError();
10809 Args[1] = ArgsRes1.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010810 break;
10811 }
10812 }
10813
Douglas Gregor33074752009-09-30 21:46:01 +000010814 case OR_No_Viable_Function: {
10815 // C++ [over.match.oper]p9:
10816 // If the operator is the operator , [...] and there are no
10817 // viable functions, then the operator is assumed to be the
10818 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +000010819 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +000010820 break;
10821
Chandler Carruth6df868e2010-12-12 08:17:55 +000010822 // For class as left operand for assignment or compound assigment
10823 // operator do not fall through to handling in built-in, but report that
10824 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +000010825 ExprResult Result = ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010826 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +000010827 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +000010828 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10829 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010830 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedman3f93d4c2013-08-28 20:35:35 +000010831 if (Args[0]->getType()->isIncompleteType()) {
10832 Diag(OpLoc, diag::note_assign_lhs_incomplete)
10833 << Args[0]->getType()
10834 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10835 }
Douglas Gregor33074752009-09-30 21:46:01 +000010836 } else {
Richard Smithf50e88a2011-06-05 22:42:48 +000010837 // This is an erroneous use of an operator which can be overloaded by
10838 // a non-member function. Check for non-member operators which were
10839 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010840 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smithf50e88a2011-06-05 22:42:48 +000010841 // FIXME: Recover by calling the found function.
10842 return ExprError();
10843
Douglas Gregor33074752009-09-30 21:46:01 +000010844 // No viable function; try to create a built-in operation, which will
10845 // produce an error. Then, show the non-viable candidates.
10846 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +000010847 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010848 assert(Result.isInvalid() &&
Douglas Gregor33074752009-09-30 21:46:01 +000010849 "C++ binary operator overloading is missing candidates!");
10850 if (Result.isInvalid())
Ahmed Charles13a140c2012-02-25 11:00:22 +000010851 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010852 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010853 return Result;
Douglas Gregor33074752009-09-30 21:46:01 +000010854 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010855
10856 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010857 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +000010858 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +000010859 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010860 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010861 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010862 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010863 return ExprError();
10864
10865 case OR_Deleted:
Douglas Gregore4e68d42012-02-15 19:33:52 +000010866 if (isImplicitlyDeleted(Best->Function)) {
10867 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10868 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smith0f46e642012-12-28 12:23:24 +000010869 << Context.getRecordType(Method->getParent())
10870 << getSpecialMember(Method);
Richard Smith5bdaac52012-04-02 20:59:25 +000010871
Richard Smith0f46e642012-12-28 12:23:24 +000010872 // The user probably meant to call this special member. Just
10873 // explain why it's deleted.
10874 NoteDeletedFunction(Method);
10875 return ExprError();
Douglas Gregore4e68d42012-02-15 19:33:52 +000010876 } else {
10877 Diag(OpLoc, diag::err_ovl_deleted_oper)
10878 << Best->Function->isDeleted()
10879 << BinaryOperator::getOpcodeStr(Opc)
10880 << getDeletedOrUnavailableSuffix(Best->Function)
10881 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10882 }
Ahmed Charles13a140c2012-02-25 11:00:22 +000010883 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman1795d372011-08-26 19:46:22 +000010884 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010885 return ExprError();
John McCall1d318332010-01-12 00:44:57 +000010886 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010887
Douglas Gregor33074752009-09-30 21:46:01 +000010888 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010889 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010890}
10891
John McCall60d7b3a2010-08-24 06:29:42 +000010892ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +000010893Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10894 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010895 Expr *Base, Expr *Idx) {
10896 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +000010897 DeclarationName OpName =
10898 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10899
10900 // If either side is type-dependent, create an appropriate dependent
10901 // expression.
10902 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10903
John McCallc373d482010-01-27 01:50:18 +000010904 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010905 // CHECKME: no 'operator' keyword?
10906 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10907 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +000010908 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010909 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010910 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010911 /*ADL*/ true, /*Overloaded*/ false,
10912 UnresolvedSetIterator(),
10913 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +000010914 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +000010915
Sebastian Redlf322ed62009-10-29 20:17:01 +000010916 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010917 Args,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010918 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010919 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +000010920 RLoc, false));
Sebastian Redlf322ed62009-10-29 20:17:01 +000010921 }
10922
John McCall5acb0c92011-10-17 18:40:02 +000010923 // Handle placeholders on both operands.
10924 if (checkPlaceholderForOverload(*this, Args[0]))
10925 return ExprError();
10926 if (checkPlaceholderForOverload(*this, Args[1]))
10927 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010928
Sebastian Redlf322ed62009-10-29 20:17:01 +000010929 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010930 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010931
10932 // Subscript can only be overloaded as a member function.
10933
10934 // Add operator candidates that are member functions.
Richard Smith958ba642013-05-05 15:51:06 +000010935 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010936
10937 // Add builtin operator candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010938 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010939
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010940 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10941
Sebastian Redlf322ed62009-10-29 20:17:01 +000010942 // Perform overload resolution.
10943 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010944 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +000010945 case OR_Success: {
10946 // We found a built-in operator or an overloaded operator.
10947 FunctionDecl *FnDecl = Best->Function;
10948
10949 if (FnDecl) {
10950 // We matched an overloaded operator. Build a call to that
10951 // operator.
10952
John McCall9aa472c2010-03-19 07:35:19 +000010953 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallc373d482010-01-27 01:50:18 +000010954
Sebastian Redlf322ed62009-10-29 20:17:01 +000010955 // Convert the arguments.
10956 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley429bb272011-04-08 18:41:53 +000010957 ExprResult Arg0 =
10958 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10959 Best->FoundDecl, Method);
10960 if (Arg0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010961 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010962 Args[0] = Arg0.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010963
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010964 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010965 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010966 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010967 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010968 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010969 SourceLocation(),
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010970 Owned(Args[1]));
10971 if (InputInit.isInvalid())
10972 return ExprError();
10973
10974 Args[1] = InputInit.takeAs<Expr>();
10975
Sebastian Redlf322ed62009-10-29 20:17:01 +000010976 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +000010977 QualType ResultTy = FnDecl->getResultType();
10978 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10979 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010980
10981 // Build the actual expression node.
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010982 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10983 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010984 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010985 Best->FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010986 HadMultipleCandidates,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010987 OpLocInfo.getLoc(),
10988 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010989 if (FnExpr.isInvalid())
10990 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010991
John McCall9ae2f072010-08-23 23:25:46 +000010992 CXXOperatorCallExpr *TheCall =
10993 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010994 FnExpr.take(), Args,
Lang Hamesbe9af122012-10-02 04:45:10 +000010995 ResultTy, VK, RLoc,
10996 false);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010997
John McCall9ae2f072010-08-23 23:25:46 +000010998 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010999 FnDecl))
11000 return ExprError();
11001
John McCall9ae2f072010-08-23 23:25:46 +000011002 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +000011003 } else {
11004 // We matched a built-in operator. Convert the arguments, then
11005 // break out so that we will build the appropriate built-in
11006 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000011007 ExprResult ArgsRes0 =
11008 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11009 Best->Conversions[0], AA_Passing);
11010 if (ArgsRes0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000011011 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011012 Args[0] = ArgsRes0.take();
11013
11014 ExprResult ArgsRes1 =
11015 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11016 Best->Conversions[1], AA_Passing);
11017 if (ArgsRes1.isInvalid())
11018 return ExprError();
11019 Args[1] = ArgsRes1.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000011020
11021 break;
11022 }
11023 }
11024
11025 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +000011026 if (CandidateSet.empty())
11027 Diag(LLoc, diag::err_ovl_no_oper)
11028 << Args[0]->getType() << /*subscript*/ 0
11029 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11030 else
11031 Diag(LLoc, diag::err_ovl_no_viable_subscript)
11032 << Args[0]->getType()
11033 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011034 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000011035 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +000011036 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000011037 }
11038
11039 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000011040 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011041 << "[]"
Douglas Gregorae2cf762010-11-13 20:06:38 +000011042 << Args[0]->getType() << Args[1]->getType()
11043 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011044 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000011045 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000011046 return ExprError();
11047
11048 case OR_Deleted:
11049 Diag(LLoc, diag::err_ovl_deleted_oper)
11050 << Best->Function->isDeleted() << "[]"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011051 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redlf322ed62009-10-29 20:17:01 +000011052 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011053 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000011054 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000011055 return ExprError();
11056 }
11057
11058 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +000011059 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000011060}
11061
Douglas Gregor88a35142008-12-22 05:46:06 +000011062/// BuildCallToMemberFunction - Build a call to a member
11063/// function. MemExpr is the expression that refers to the member
11064/// function (and includes the object parameter), Args/NumArgs are the
11065/// arguments to the function call (not including the object
11066/// parameter). The caller needs to validate that the member
John McCall864c0412011-04-26 20:42:42 +000011067/// expression refers to a non-static member function or an overloaded
11068/// member function.
John McCall60d7b3a2010-08-24 06:29:42 +000011069ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +000011070Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011071 SourceLocation LParenLoc,
11072 MultiExprArg Args,
11073 SourceLocation RParenLoc) {
John McCall864c0412011-04-26 20:42:42 +000011074 assert(MemExprE->getType() == Context.BoundMemberTy ||
11075 MemExprE->getType() == Context.OverloadTy);
11076
Douglas Gregor88a35142008-12-22 05:46:06 +000011077 // Dig out the member expression. This holds both the object
11078 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +000011079 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011080
John McCall864c0412011-04-26 20:42:42 +000011081 // Determine whether this is a call to a pointer-to-member function.
11082 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11083 assert(op->getType() == Context.BoundMemberTy);
11084 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
11085
11086 QualType fnType =
11087 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11088
11089 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11090 QualType resultType = proto->getCallResultType(Context);
11091 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
11092
11093 // Check that the object type isn't more qualified than the
11094 // member function we're calling.
11095 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11096
11097 QualType objectType = op->getLHS()->getType();
11098 if (op->getOpcode() == BO_PtrMemI)
11099 objectType = objectType->castAs<PointerType>()->getPointeeType();
11100 Qualifiers objectQuals = objectType.getQualifiers();
11101
11102 Qualifiers difference = objectQuals - funcQuals;
11103 difference.removeObjCGCAttr();
11104 difference.removeAddressSpace();
11105 if (difference) {
11106 std::string qualsString = difference.getAsString();
11107 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11108 << fnType.getUnqualifiedType()
11109 << qualsString
11110 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11111 }
11112
11113 CXXMemberCallExpr *call
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011114 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall864c0412011-04-26 20:42:42 +000011115 resultType, valueKind, RParenLoc);
11116
11117 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +000011118 op->getRHS()->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +000011119 call, 0))
11120 return ExprError();
11121
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011122 if (ConvertArgumentsForCall(call, op, 0, proto, Args, RParenLoc))
John McCall864c0412011-04-26 20:42:42 +000011123 return ExprError();
11124
Richard Trieue2a90b82013-06-22 02:30:38 +000011125 if (CheckOtherCall(call, proto))
11126 return ExprError();
11127
John McCall864c0412011-04-26 20:42:42 +000011128 return MaybeBindToTemporary(call);
11129 }
11130
John McCall5acb0c92011-10-17 18:40:02 +000011131 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011132 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall5acb0c92011-10-17 18:40:02 +000011133 return ExprError();
11134
John McCall129e2df2009-11-30 22:42:35 +000011135 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +000011136 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +000011137 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +000011138 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +000011139 if (isa<MemberExpr>(NakedMemExpr)) {
11140 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +000011141 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +000011142 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +000011143 Qualifier = MemExpr->getQualifier();
John McCall5acb0c92011-10-17 18:40:02 +000011144 UnbridgedCasts.restore();
John McCall129e2df2009-11-30 22:42:35 +000011145 } else {
11146 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +000011147 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011148
John McCall701c89e2009-12-03 04:06:58 +000011149 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011150 Expr::Classification ObjectClassification
11151 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11152 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +000011153
Douglas Gregor88a35142008-12-22 05:46:06 +000011154 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +000011155 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +000011156
John McCallaa81e162009-12-01 22:10:20 +000011157 // FIXME: avoid copy.
11158 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11159 if (UnresExpr->hasExplicitTemplateArgs()) {
11160 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11161 TemplateArgs = &TemplateArgsBuffer;
11162 }
11163
John McCall129e2df2009-11-30 22:42:35 +000011164 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11165 E = UnresExpr->decls_end(); I != E; ++I) {
11166
John McCall701c89e2009-12-03 04:06:58 +000011167 NamedDecl *Func = *I;
11168 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11169 if (isa<UsingShadowDecl>(Func))
11170 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11171
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011172
Francois Pichetdbee3412011-01-18 05:04:39 +000011173 // Microsoft supports direct constructor calls.
David Blaikie4e4d0842012-03-11 07:00:24 +000011174 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charles13a140c2012-02-25 11:00:22 +000011175 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011176 Args, CandidateSet);
Francois Pichetdbee3412011-01-18 05:04:39 +000011177 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000011178 // If explicit template arguments were provided, we can't call a
11179 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +000011180 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000011181 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011182
John McCall9aa472c2010-03-19 07:35:19 +000011183 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011184 ObjectClassification, Args, CandidateSet,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011185 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000011186 } else {
John McCall129e2df2009-11-30 22:42:35 +000011187 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +000011188 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011189 ObjectType, ObjectClassification,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011190 Args, CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +000011191 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000011192 }
Douglas Gregordec06662009-08-21 18:42:58 +000011193 }
Mike Stump1eb44332009-09-09 15:08:12 +000011194
John McCall129e2df2009-11-30 22:42:35 +000011195 DeclarationName DeclName = UnresExpr->getMemberName();
11196
John McCall5acb0c92011-10-17 18:40:02 +000011197 UnbridgedCasts.restore();
11198
Douglas Gregor88a35142008-12-22 05:46:06 +000011199 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000011200 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +000011201 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +000011202 case OR_Success:
11203 Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +000011204 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +000011205 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +000011206 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11207 return ExprError();
Faisal Valid570a922013-06-15 11:54:37 +000011208 // If FoundDecl is different from Method (such as if one is a template
11209 // and the other a specialization), make sure DiagnoseUseOfDecl is
11210 // called on both.
11211 // FIXME: This would be more comprehensively addressed by modifying
11212 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11213 // being used.
11214 if (Method != FoundDecl.getDecl() &&
11215 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11216 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000011217 break;
11218
11219 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +000011220 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +000011221 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000011222 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011223 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor88a35142008-12-22 05:46:06 +000011224 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000011225 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000011226
11227 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +000011228 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000011229 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011230 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor88a35142008-12-22 05:46:06 +000011231 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000011232 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011233
11234 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +000011235 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011236 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011237 << DeclName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011238 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011239 << MemExprE->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011240 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011241 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000011242 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000011243 }
11244
John McCall6bb80172010-03-30 21:47:33 +000011245 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +000011246
John McCallaa81e162009-12-01 22:10:20 +000011247 // If overload resolution picked a static member, build a
11248 // non-member call based on that function.
11249 if (Method->isStatic()) {
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011250 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11251 RParenLoc);
John McCallaa81e162009-12-01 22:10:20 +000011252 }
11253
John McCall129e2df2009-11-30 22:42:35 +000011254 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +000011255 }
11256
John McCallf89e55a2010-11-18 06:31:45 +000011257 QualType ResultType = Method->getResultType();
11258 ExprValueKind VK = Expr::getValueKindForType(ResultType);
11259 ResultType = ResultType.getNonLValueExprType(Context);
11260
Douglas Gregor88a35142008-12-22 05:46:06 +000011261 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011262 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011263 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCallf89e55a2010-11-18 06:31:45 +000011264 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +000011265
Anders Carlssoneed3e692009-10-10 00:06:20 +000011266 // Check for a valid return type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011267 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +000011268 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +000011269 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011270
Douglas Gregor88a35142008-12-22 05:46:06 +000011271 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +000011272 // We only need to do this if there was actually an overload; otherwise
11273 // it was done at lookup.
John Wiegley429bb272011-04-08 18:41:53 +000011274 if (!Method->isStatic()) {
11275 ExprResult ObjectArg =
11276 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11277 FoundDecl, Method);
11278 if (ObjectArg.isInvalid())
11279 return ExprError();
11280 MemExpr->setBase(ObjectArg.take());
11281 }
Douglas Gregor88a35142008-12-22 05:46:06 +000011282
11283 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +000011284 const FunctionProtoType *Proto =
11285 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011286 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor88a35142008-12-22 05:46:06 +000011287 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +000011288 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000011289
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011290 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmane61eb042012-02-18 04:48:30 +000011291
Richard Smith831421f2012-06-25 20:30:08 +000011292 if (CheckFunctionCall(Method, TheCall, Proto))
John McCallaa81e162009-12-01 22:10:20 +000011293 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +000011294
Anders Carlsson2174d4c2011-05-06 14:25:31 +000011295 if ((isa<CXXConstructorDecl>(CurContext) ||
11296 isa<CXXDestructorDecl>(CurContext)) &&
11297 TheCall->getMethodDecl()->isPure()) {
11298 const CXXMethodDecl *MD = TheCall->getMethodDecl();
11299
Chandler Carruthae198062011-06-27 08:31:58 +000011300 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson2174d4c2011-05-06 14:25:31 +000011301 Diag(MemExpr->getLocStart(),
11302 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11303 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11304 << MD->getParent()->getDeclName();
11305
11306 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruthae198062011-06-27 08:31:58 +000011307 }
Anders Carlsson2174d4c2011-05-06 14:25:31 +000011308 }
John McCall9ae2f072010-08-23 23:25:46 +000011309 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +000011310}
11311
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011312/// BuildCallToObjectOfClassType - Build a call to an object of class
11313/// type (C++ [over.call.object]), which can end up invoking an
11314/// overloaded function call operator (@c operator()) or performing a
11315/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +000011316ExprResult
John Wiegley429bb272011-04-08 18:41:53 +000011317Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregor5c37de72008-12-06 00:22:45 +000011318 SourceLocation LParenLoc,
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011319 MultiExprArg Args,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011320 SourceLocation RParenLoc) {
John McCall5acb0c92011-10-17 18:40:02 +000011321 if (checkPlaceholderForOverload(*this, Obj))
11322 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011323 ExprResult Object = Owned(Obj);
John McCall5acb0c92011-10-17 18:40:02 +000011324
11325 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011326 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall5acb0c92011-10-17 18:40:02 +000011327 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000011328
John Wiegley429bb272011-04-08 18:41:53 +000011329 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
11330 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +000011331
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011332 // C++ [over.call.object]p1:
11333 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +000011334 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011335 // candidate functions includes at least the function call
11336 // operators of T. The function call operators of T are obtained by
11337 // ordinary lookup of the name operator() in the context of
11338 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +000011339 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +000011340 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +000011341
John Wiegley429bb272011-04-08 18:41:53 +000011342 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000011343 diag::err_incomplete_object_call, Object.get()))
Douglas Gregor593564b2009-11-15 07:48:03 +000011344 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011345
John McCalla24dc2e2009-11-17 02:14:36 +000011346 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11347 LookupQualifiedName(R, Record->getDecl());
11348 R.suppressDiagnostics();
11349
Douglas Gregor593564b2009-11-15 07:48:03 +000011350 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +000011351 Oper != OperEnd; ++Oper) {
John Wiegley429bb272011-04-08 18:41:53 +000011352 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011353 Object.get()->Classify(Context),
11354 Args, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +000011355 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +000011356 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011357
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011358 // C++ [over.call.object]p2:
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011359 // In addition, for each (non-explicit in C++0x) conversion function
11360 // declared in T of the form
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011361 //
11362 // operator conversion-type-id () cv-qualifier;
11363 //
11364 // where cv-qualifier is the same cv-qualification as, or a
11365 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +000011366 // denotes the type "pointer to function of (P1,...,Pn) returning
11367 // R", or the type "reference to pointer to function of
11368 // (P1,...,Pn) returning R", or the type "reference to function
11369 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011370 // is also considered as a candidate function. Similarly,
11371 // surrogate call functions are added to the set of candidate
11372 // functions for each conversion function declared in an
11373 // accessible base class provided the function is not hidden
11374 // within T by another intervening declaration.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000011375 std::pair<CXXRecordDecl::conversion_iterator,
11376 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregor90073282010-01-11 19:36:35 +000011377 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000011378 for (CXXRecordDecl::conversion_iterator
11379 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +000011380 NamedDecl *D = *I;
11381 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11382 if (isa<UsingShadowDecl>(D))
11383 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011384
Douglas Gregor4a27d702009-10-21 06:18:39 +000011385 // Skip over templated conversion functions; they aren't
11386 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +000011387 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +000011388 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +000011389
John McCall701c89e2009-12-03 04:06:58 +000011390 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011391 if (!Conv->isExplicit()) {
11392 // Strip the reference type (if any) and then the pointer type (if
11393 // any) to get down to what might be a function type.
11394 QualType ConvType = Conv->getConversionType().getNonReferenceType();
11395 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11396 ConvType = ConvPtrType->getPointeeType();
John McCallba135432009-11-21 08:51:07 +000011397
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011398 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11399 {
11400 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011401 Object.get(), Args, CandidateSet);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011402 }
11403 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011404 }
Mike Stump1eb44332009-09-09 15:08:12 +000011405
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011406 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11407
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011408 // Perform overload resolution.
11409 OverloadCandidateSet::iterator Best;
John Wiegley429bb272011-04-08 18:41:53 +000011410 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall120d63c2010-08-24 20:38:10 +000011411 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011412 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011413 // Overload resolution succeeded; we'll build the appropriate call
11414 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011415 break;
11416
11417 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +000011418 if (CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +000011419 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley429bb272011-04-08 18:41:53 +000011420 << Object.get()->getType() << /*call*/ 1
11421 << Object.get()->getSourceRange();
John McCall1eb3e102010-01-07 02:04:15 +000011422 else
Daniel Dunbar96a00142012-03-09 18:35:03 +000011423 Diag(Object.get()->getLocStart(),
John McCall1eb3e102010-01-07 02:04:15 +000011424 diag::err_ovl_no_viable_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000011425 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011426 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011427 break;
11428
11429 case OR_Ambiguous:
Daniel Dunbar96a00142012-03-09 18:35:03 +000011430 Diag(Object.get()->getLocStart(),
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011431 diag::err_ovl_ambiguous_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000011432 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011433 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011434 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011435
11436 case OR_Deleted:
Daniel Dunbar96a00142012-03-09 18:35:03 +000011437 Diag(Object.get()->getLocStart(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011438 diag::err_ovl_deleted_object_call)
11439 << Best->Function->isDeleted()
John Wiegley429bb272011-04-08 18:41:53 +000011440 << Object.get()->getType()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011441 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley429bb272011-04-08 18:41:53 +000011442 << Object.get()->getSourceRange();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011443 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011444 break;
Mike Stump1eb44332009-09-09 15:08:12 +000011445 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011446
Douglas Gregorff331c12010-07-25 18:17:45 +000011447 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011448 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011449
John McCall5acb0c92011-10-17 18:40:02 +000011450 UnbridgedCasts.restore();
11451
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011452 if (Best->Function == 0) {
11453 // Since there is no function declaration, this is one of the
11454 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +000011455 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011456 = cast<CXXConversionDecl>(
11457 Best->Conversions[0].UserDefined.ConversionFunction);
11458
John Wiegley429bb272011-04-08 18:41:53 +000011459 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +000011460 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11461 return ExprError();
Faisal Valid570a922013-06-15 11:54:37 +000011462 assert(Conv == Best->FoundDecl.getDecl() &&
11463 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011464 // We selected one of the surrogate functions that converts the
11465 // object parameter to a function pointer. Perform the conversion
11466 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011467
Fariborz Jahaniand8307b12009-09-28 18:35:46 +000011468 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +000011469 // and then call it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011470 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11471 Conv, HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +000011472 if (Call.isInvalid())
11473 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +000011474 // Record usage of conversion in an implicit cast.
11475 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
11476 CK_UserDefinedConversion,
11477 Call.get(), 0, VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011478
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011479 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011480 }
11481
John Wiegley429bb272011-04-08 18:41:53 +000011482 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall41d89032010-01-28 01:54:34 +000011483
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011484 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11485 // that calls this method, using Object for the implicit object
11486 // parameter and passing along the remaining arguments.
11487 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Webere0ff6902012-11-09 06:06:14 +000011488
11489 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber1a52a4d2012-11-09 08:38:04 +000011490 if (Method->isInvalidDecl())
Nico Webere0ff6902012-11-09 06:06:14 +000011491 return ExprError();
11492
Chandler Carruth6df868e2010-12-12 08:17:55 +000011493 const FunctionProtoType *Proto =
11494 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011495
11496 unsigned NumArgsInProto = Proto->getNumArgs();
Mike Stump1eb44332009-09-09 15:08:12 +000011497
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011498 DeclarationNameInfo OpLocInfo(
11499 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11500 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011501 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011502 HadMultipleCandidates,
11503 OpLocInfo.getLoc(),
11504 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000011505 if (NewFn.isInvalid())
11506 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011507
Benjamin Kramer7034fae2013-09-25 13:10:11 +000011508 // Build the full argument list for the method call (the implicit object
11509 // parameter is placed at the beginning of the list).
11510 llvm::OwningArrayPtr<Expr *> MethodArgs(new Expr*[Args.size() + 1]);
11511 MethodArgs[0] = Object.get();
11512 std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
11513
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011514 // Once we've built TheCall, all of the expressions are properly
11515 // owned.
John McCallf89e55a2010-11-18 06:31:45 +000011516 QualType ResultTy = Method->getResultType();
11517 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11518 ResultTy = ResultTy.getNonLValueExprType(Context);
11519
Benjamin Kramer7034fae2013-09-25 13:10:11 +000011520 CXXOperatorCallExpr *TheCall = new (Context)
11521 CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
11522 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
11523 ResultTy, VK, RParenLoc, false);
11524 MethodArgs.reset();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011525
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011526 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +000011527 Method))
11528 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011529
Douglas Gregor518fda12009-01-13 05:10:00 +000011530 // We may have default arguments. If so, we need to allocate more
11531 // slots in the call for them.
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011532 if (Args.size() < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +000011533 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +000011534
Chris Lattner312531a2009-04-12 08:11:20 +000011535 bool IsError = false;
11536
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011537 // Initialize the implicit object parameter.
John Wiegley429bb272011-04-08 18:41:53 +000011538 ExprResult ObjRes =
11539 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11540 Best->FoundDecl, Method);
11541 if (ObjRes.isInvalid())
11542 IsError = true;
11543 else
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011544 Object = ObjRes;
John Wiegley429bb272011-04-08 18:41:53 +000011545 TheCall->setArg(0, Object.take());
Chris Lattner312531a2009-04-12 08:11:20 +000011546
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011547 // Check the argument types.
Benjamin Kramer83372f82013-10-05 10:03:01 +000011548 for (unsigned i = 0; i != NumArgsInProto; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011549 Expr *Arg;
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011550 if (i < Args.size()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011551 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +000011552
Douglas Gregor518fda12009-01-13 05:10:00 +000011553 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +000011554
John McCall60d7b3a2010-08-24 06:29:42 +000011555 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +000011556 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000011557 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +000011558 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +000011559 SourceLocation(), Arg);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011560
Anders Carlsson3faa4862010-01-29 18:43:53 +000011561 IsError |= InputInit.isInvalid();
11562 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011563 } else {
John McCall60d7b3a2010-08-24 06:29:42 +000011564 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +000011565 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11566 if (DefArg.isInvalid()) {
11567 IsError = true;
11568 break;
11569 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011570
Douglas Gregord47c47d2009-11-09 19:27:57 +000011571 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011572 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011573
11574 TheCall->setArg(i + 1, Arg);
11575 }
11576
11577 // If this is a variadic call, handle args passed through "...".
11578 if (Proto->isVariadic()) {
11579 // Promote the arguments (C99 6.5.2.2p7).
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011580 for (unsigned i = NumArgsInProto, e = Args.size(); i < e; i++) {
John Wiegley429bb272011-04-08 18:41:53 +000011581 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11582 IsError |= Arg.isInvalid();
11583 TheCall->setArg(i + 1, Arg.take());
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011584 }
11585 }
11586
Chris Lattner312531a2009-04-12 08:11:20 +000011587 if (IsError) return true;
11588
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011589 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmane61eb042012-02-18 04:48:30 +000011590
Richard Smith831421f2012-06-25 20:30:08 +000011591 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +000011592 return true;
11593
John McCall182f7092010-08-24 06:09:16 +000011594 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011595}
11596
Douglas Gregor8ba10742008-11-20 16:27:02 +000011597/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +000011598/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +000011599/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +000011600ExprResult
Kaelyn Uhrainbaaeb852013-07-31 17:38:24 +000011601Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
11602 bool *NoArrowOperatorFound) {
Chandler Carruth6df868e2010-12-12 08:17:55 +000011603 assert(Base->getType()->isRecordType() &&
11604 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +000011605
John McCall5acb0c92011-10-17 18:40:02 +000011606 if (checkPlaceholderForOverload(*this, Base))
11607 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000011608
John McCall5769d612010-02-08 23:07:23 +000011609 SourceLocation Loc = Base->getExprLoc();
11610
Douglas Gregor8ba10742008-11-20 16:27:02 +000011611 // C++ [over.ref]p1:
11612 //
11613 // [...] An expression x->m is interpreted as (x.operator->())->m
11614 // for a class object x of type T if T::operator->() exists and if
11615 // the operator is selected as the best match function by the
11616 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +000011617 DeclarationName OpName =
11618 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +000011619 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +000011620 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011621
John McCall5769d612010-02-08 23:07:23 +000011622 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000011623 diag::err_typecheck_incomplete_tag, Base))
Eli Friedmanf43fb722009-11-18 01:28:03 +000011624 return ExprError();
11625
John McCalla24dc2e2009-11-17 02:14:36 +000011626 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11627 LookupQualifiedName(R, BaseRecord->getDecl());
11628 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +000011629
11630 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +000011631 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011632 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko55431692013-05-05 00:41:58 +000011633 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +000011634 }
Douglas Gregor8ba10742008-11-20 16:27:02 +000011635
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011636 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11637
Douglas Gregor8ba10742008-11-20 16:27:02 +000011638 // Perform overload resolution.
11639 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000011640 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +000011641 case OR_Success:
11642 // Overload resolution succeeded; we'll build the call below.
11643 break;
11644
11645 case OR_No_Viable_Function:
Kaelyn Uhrain45c3ba72013-07-11 22:38:30 +000011646 if (CandidateSet.empty()) {
11647 QualType BaseType = Base->getType();
Kaelyn Uhrainbaaeb852013-07-31 17:38:24 +000011648 if (NoArrowOperatorFound) {
11649 // Report this specific error to the caller instead of emitting a
11650 // diagnostic, as requested.
11651 *NoArrowOperatorFound = true;
11652 return ExprError();
11653 }
Kaelyn Uhraind4224342013-07-15 19:54:54 +000011654 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
11655 << BaseType << Base->getSourceRange();
Kaelyn Uhrain45c3ba72013-07-11 22:38:30 +000011656 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhraind4224342013-07-15 19:54:54 +000011657 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain45c3ba72013-07-11 22:38:30 +000011658 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain45c3ba72013-07-11 22:38:30 +000011659 }
11660 } else
Douglas Gregor8ba10742008-11-20 16:27:02 +000011661 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011662 << "operator->" << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011663 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011664 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011665
11666 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000011667 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11668 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011669 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011670 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011671
11672 case OR_Deleted:
11673 Diag(OpLoc, diag::err_ovl_deleted_oper)
11674 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011675 << "->"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011676 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011677 << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011678 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011679 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011680 }
11681
John McCall9aa472c2010-03-19 07:35:19 +000011682 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
11683
Douglas Gregor8ba10742008-11-20 16:27:02 +000011684 // Convert the object parameter.
11685 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000011686 ExprResult BaseResult =
11687 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11688 Best->FoundDecl, Method);
11689 if (BaseResult.isInvalid())
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011690 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011691 Base = BaseResult.take();
Douglas Gregorfc195ef2008-11-21 03:04:22 +000011692
Douglas Gregor8ba10742008-11-20 16:27:02 +000011693 // Build the operator call.
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011694 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011695 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000011696 if (FnExpr.isInvalid())
11697 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011698
John McCallf89e55a2010-11-18 06:31:45 +000011699 QualType ResultTy = Method->getResultType();
11700 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11701 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +000011702 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011703 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000011704 Base, ResultTy, VK, OpLoc, false);
Anders Carlsson15ea3782009-10-13 22:43:21 +000011705
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011706 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000011707 Method))
11708 return ExprError();
Eli Friedmand5931902011-04-04 01:18:25 +000011709
11710 return MaybeBindToTemporary(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +000011711}
11712
Richard Smith36f5cfe2012-03-09 08:00:36 +000011713/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11714/// a literal operator described by the provided lookup results.
11715ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11716 DeclarationNameInfo &SuffixInfo,
11717 ArrayRef<Expr*> Args,
11718 SourceLocation LitEndLoc,
11719 TemplateArgumentListInfo *TemplateArgs) {
11720 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smith9fcce652012-03-07 08:35:16 +000011721
Richard Smith36f5cfe2012-03-09 08:00:36 +000011722 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11723 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11724 TemplateArgs);
Richard Smith9fcce652012-03-07 08:35:16 +000011725
Richard Smith36f5cfe2012-03-09 08:00:36 +000011726 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11727
Richard Smith36f5cfe2012-03-09 08:00:36 +000011728 // Perform overload resolution. This will usually be trivial, but might need
11729 // to perform substitutions for a literal operator template.
11730 OverloadCandidateSet::iterator Best;
11731 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11732 case OR_Success:
11733 case OR_Deleted:
11734 break;
11735
11736 case OR_No_Viable_Function:
11737 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11738 << R.getLookupName();
11739 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11740 return ExprError();
11741
11742 case OR_Ambiguous:
11743 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11744 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11745 return ExprError();
Richard Smith9fcce652012-03-07 08:35:16 +000011746 }
11747
Richard Smith36f5cfe2012-03-09 08:00:36 +000011748 FunctionDecl *FD = Best->Function;
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011749 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
11750 HadMultipleCandidates,
Richard Smith36f5cfe2012-03-09 08:00:36 +000011751 SuffixInfo.getLoc(),
11752 SuffixInfo.getInfo());
11753 if (Fn.isInvalid())
11754 return true;
Richard Smith9fcce652012-03-07 08:35:16 +000011755
11756 // Check the argument types. This should almost always be a no-op, except
11757 // that array-to-pointer decay is applied to string literals.
Richard Smith9fcce652012-03-07 08:35:16 +000011758 Expr *ConvArgs[2];
Richard Smith958ba642013-05-05 15:51:06 +000011759 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smith9fcce652012-03-07 08:35:16 +000011760 ExprResult InputInit = PerformCopyInitialization(
11761 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11762 SourceLocation(), Args[ArgIdx]);
11763 if (InputInit.isInvalid())
11764 return true;
11765 ConvArgs[ArgIdx] = InputInit.take();
11766 }
11767
Richard Smith9fcce652012-03-07 08:35:16 +000011768 QualType ResultTy = FD->getResultType();
11769 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11770 ResultTy = ResultTy.getNonLValueExprType(Context);
11771
Richard Smith9fcce652012-03-07 08:35:16 +000011772 UserDefinedLiteral *UDL =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000011773 new (Context) UserDefinedLiteral(Context, Fn.take(),
11774 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smith9fcce652012-03-07 08:35:16 +000011775 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11776
11777 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11778 return ExprError();
11779
Richard Smith831421f2012-06-25 20:30:08 +000011780 if (CheckFunctionCall(FD, UDL, NULL))
Richard Smith9fcce652012-03-07 08:35:16 +000011781 return ExprError();
11782
11783 return MaybeBindToTemporary(UDL);
11784}
11785
Sam Panzere1715b62012-08-21 00:52:01 +000011786/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11787/// given LookupResult is non-empty, it is assumed to describe a member which
11788/// will be invoked. Otherwise, the function will be found via argument
11789/// dependent lookup.
11790/// CallExpr is set to a valid expression and FRS_Success returned on success,
11791/// otherwise CallExpr is set to ExprError() and some non-success value
11792/// is returned.
11793Sema::ForRangeStatus
11794Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11795 SourceLocation RangeLoc, VarDecl *Decl,
11796 BeginEndFunction BEF,
11797 const DeclarationNameInfo &NameInfo,
11798 LookupResult &MemberLookup,
11799 OverloadCandidateSet *CandidateSet,
11800 Expr *Range, ExprResult *CallExpr) {
11801 CandidateSet->clear();
11802 if (!MemberLookup.empty()) {
11803 ExprResult MemberRef =
11804 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11805 /*IsPtr=*/false, CXXScopeSpec(),
11806 /*TemplateKWLoc=*/SourceLocation(),
11807 /*FirstQualifierInScope=*/0,
11808 MemberLookup,
11809 /*TemplateArgs=*/0);
11810 if (MemberRef.isInvalid()) {
11811 *CallExpr = ExprError();
11812 Diag(Range->getLocStart(), diag::note_in_for_range)
11813 << RangeLoc << BEF << Range->getType();
11814 return FRS_DiagnosticIssued;
11815 }
Dmitri Gribenko62ed8892013-05-05 20:40:26 +000011816 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, 0);
Sam Panzere1715b62012-08-21 00:52:01 +000011817 if (CallExpr->isInvalid()) {
11818 *CallExpr = ExprError();
11819 Diag(Range->getLocStart(), diag::note_in_for_range)
11820 << RangeLoc << BEF << Range->getType();
11821 return FRS_DiagnosticIssued;
11822 }
11823 } else {
11824 UnresolvedSet<0> FoundNames;
Sam Panzere1715b62012-08-21 00:52:01 +000011825 UnresolvedLookupExpr *Fn =
11826 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11827 NestedNameSpecifierLoc(), NameInfo,
11828 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb1502bc2012-10-18 17:56:02 +000011829 FoundNames.begin(), FoundNames.end());
Sam Panzere1715b62012-08-21 00:52:01 +000011830
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011831 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzere1715b62012-08-21 00:52:01 +000011832 CandidateSet, CallExpr);
11833 if (CandidateSet->empty() || CandidateSetError) {
11834 *CallExpr = ExprError();
11835 return FRS_NoViableFunction;
11836 }
11837 OverloadCandidateSet::iterator Best;
11838 OverloadingResult OverloadResult =
11839 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
11840
11841 if (OverloadResult == OR_No_Viable_Function) {
11842 *CallExpr = ExprError();
11843 return FRS_NoViableFunction;
11844 }
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011845 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Sam Panzere1715b62012-08-21 00:52:01 +000011846 Loc, 0, CandidateSet, &Best,
11847 OverloadResult,
11848 /*AllowTypoCorrection=*/false);
11849 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
11850 *CallExpr = ExprError();
11851 Diag(Range->getLocStart(), diag::note_in_for_range)
11852 << RangeLoc << BEF << Range->getType();
11853 return FRS_DiagnosticIssued;
11854 }
11855 }
11856 return FRS_Success;
11857}
11858
11859
Douglas Gregor904eed32008-11-10 20:40:00 +000011860/// FixOverloadedFunctionReference - E is an expression that refers to
11861/// a C++ overloaded function (possibly with some parentheses and
11862/// perhaps a '&' around it). We have resolved the overloaded function
11863/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +000011864/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +000011865Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +000011866 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +000011867 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011868 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11869 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011870 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011871 return PE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011872
Douglas Gregor699ee522009-11-20 19:42:02 +000011873 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011874 }
11875
Douglas Gregor699ee522009-11-20 19:42:02 +000011876 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011877 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11878 Found, Fn);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011879 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +000011880 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +000011881 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +000011882 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +000011883 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011884 return ICE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011885
11886 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallf871d0c2010-08-07 06:22:56 +000011887 ICE->getCastKind(),
11888 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +000011889 ICE->getValueKind());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011890 }
11891
Douglas Gregor699ee522009-11-20 19:42:02 +000011892 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +000011893 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +000011894 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +000011895 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11896 if (Method->isStatic()) {
11897 // Do nothing: static member functions aren't any different
11898 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +000011899 } else {
John McCallf7a1a742009-11-24 19:00:30 +000011900 // Fix the sub expression, which really has to be an
11901 // UnresolvedLookupExpr holding an overloaded member function
11902 // or template.
John McCall6bb80172010-03-30 21:47:33 +000011903 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11904 Found, Fn);
John McCallba135432009-11-21 08:51:07 +000011905 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011906 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +000011907
John McCallba135432009-11-21 08:51:07 +000011908 assert(isa<DeclRefExpr>(SubExpr)
11909 && "fixed to something other than a decl ref");
11910 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11911 && "fixed to a member ref with no nested name qualifier");
11912
11913 // We have taken the address of a pointer to member
11914 // function. Perform the computation here so that we get the
11915 // appropriate pointer to member type.
11916 QualType ClassType
11917 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11918 QualType MemPtrType
11919 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11920
John McCallf89e55a2010-11-18 06:31:45 +000011921 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11922 VK_RValue, OK_Ordinary,
11923 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +000011924 }
11925 }
John McCall6bb80172010-03-30 21:47:33 +000011926 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11927 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011928 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011929 return UnOp;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011930
John McCall2de56d12010-08-25 11:45:40 +000011931 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +000011932 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +000011933 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +000011934 UnOp->getOperatorLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011935 }
John McCallba135432009-11-21 08:51:07 +000011936
11937 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +000011938 // FIXME: avoid copy.
11939 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +000011940 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +000011941 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11942 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +000011943 }
11944
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011945 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11946 ULE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011947 ULE->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011948 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011949 /*enclosing*/ false, // FIXME?
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011950 ULE->getNameLoc(),
11951 Fn->getType(),
11952 VK_LValue,
11953 Found.getDecl(),
11954 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011955 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011956 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11957 return DRE;
John McCallba135432009-11-21 08:51:07 +000011958 }
11959
John McCall129e2df2009-11-30 22:42:35 +000011960 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +000011961 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +000011962 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11963 if (MemExpr->hasExplicitTemplateArgs()) {
11964 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11965 TemplateArgs = &TemplateArgsBuffer;
11966 }
John McCalld5532b62009-11-23 01:53:49 +000011967
John McCallaa81e162009-12-01 22:10:20 +000011968 Expr *Base;
11969
John McCallf89e55a2010-11-18 06:31:45 +000011970 // If we're filling in a static method where we used to have an
11971 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +000011972 if (MemExpr->isImplicitAccess()) {
11973 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011974 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11975 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011976 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011977 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011978 /*enclosing*/ false,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011979 MemExpr->getMemberLoc(),
11980 Fn->getType(),
11981 VK_LValue,
11982 Found.getDecl(),
11983 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011984 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011985 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11986 return DRE;
Douglas Gregor828a1972010-01-07 23:12:05 +000011987 } else {
11988 SourceLocation Loc = MemExpr->getMemberLoc();
11989 if (MemExpr->getQualifier())
Douglas Gregor4c9be892011-02-28 20:01:57 +000011990 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman72899c32012-01-07 04:59:52 +000011991 CheckCXXThisCapture(Loc);
Douglas Gregor828a1972010-01-07 23:12:05 +000011992 Base = new (Context) CXXThisExpr(Loc,
11993 MemExpr->getBaseType(),
11994 /*isImplicit=*/true);
11995 }
John McCallaa81e162009-12-01 22:10:20 +000011996 } else
John McCall3fa5cae2010-10-26 07:05:15 +000011997 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +000011998
John McCallf5307512011-04-27 00:36:17 +000011999 ExprValueKind valueKind;
12000 QualType type;
12001 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12002 valueKind = VK_LValue;
12003 type = Fn->getType();
12004 } else {
12005 valueKind = VK_RValue;
12006 type = Context.BoundMemberTy;
12007 }
12008
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000012009 MemberExpr *ME = MemberExpr::Create(Context, Base,
12010 MemExpr->isArrow(),
12011 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000012012 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000012013 Fn,
12014 Found,
12015 MemExpr->getMemberNameInfo(),
12016 TemplateArgs,
12017 type, valueKind, OK_Ordinary);
12018 ME->setHadMultipleCandidates(true);
Richard Smith4a030222012-11-14 07:06:31 +000012019 MarkMemberReferenced(ME);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000012020 return ME;
Douglas Gregor699ee522009-11-20 19:42:02 +000012021 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000012022
John McCall3fa5cae2010-10-26 07:05:15 +000012023 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregor904eed32008-11-10 20:40:00 +000012024}
12025
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000012026ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCall60d7b3a2010-08-24 06:29:42 +000012027 DeclAccessPair Found,
12028 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +000012029 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +000012030}
12031
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000012032} // end namespace clang