blob: fae4d0232153280ddccd184ffed72c75291fa6da [file] [log] [blame]
Nick Lewycky5d9484d2013-01-24 01:12:16 +00001//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carruth55fc8732012-12-04 09:13:33 +000014#include "clang/Sema/Overload.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000015#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000018#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000019#include "clang/AST/ExprCXX.h"
John McCall0e800c92010-12-04 08:14:53 +000020#include "clang/AST/ExprObjC.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000022#include "clang/Basic/Diagnostic.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000024#include "clang/Lex/Preprocessor.h"
25#include "clang/Sema/Initialization.h"
26#include "clang/Sema/Lookup.h"
27#include "clang/Sema/SemaInternal.h"
28#include "clang/Sema/Template.h"
29#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor661b4932010-09-12 04:28:07 +000030#include "llvm/ADT/DenseSet.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000031#include "llvm/ADT/STLExtras.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000032#include "llvm/ADT/SmallPtrSet.h"
Richard Smithb8590f32012-05-07 09:03:25 +000033#include "llvm/ADT/SmallString.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000034#include <algorithm>
35
36namespace clang {
John McCall2a7fb272010-08-25 05:32:35 +000037using namespace sema;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000038
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000039/// A convenience routine for creating a decayed reference to a function.
John Wiegley429bb272011-04-08 18:41:53 +000040static ExprResult
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000041CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
42 bool HadMultipleCandidates,
Douglas Gregor5b8968c2011-07-15 16:25:15 +000043 SourceLocation Loc = SourceLocation(),
44 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Richard Smith82f145d2013-05-04 06:44:46 +000045 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
Faisal Valid570a922013-06-15 11:54:37 +000046 return ExprError();
47 // If FoundDecl is different from Fn (such as if one is a template
48 // and the other a specialization), make sure DiagnoseUseOfDecl is
49 // called on both.
50 // FIXME: This would be more comprehensively addressed by modifying
51 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
52 // being used.
53 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
Richard Smith82f145d2013-05-04 06:44:46 +000054 return ExprError();
John McCallf4b88a42012-03-10 09:33:50 +000055 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000056 VK_LValue, Loc, LocInfo);
57 if (HadMultipleCandidates)
58 DRE->setHadMultipleCandidates(true);
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000059
60 S.MarkDeclRefReferenced(DRE);
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000061
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000062 ExprResult E = S.Owned(DRE);
John Wiegley429bb272011-04-08 18:41:53 +000063 E = S.DefaultFunctionArrayConversion(E.take());
64 if (E.isInvalid())
65 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000066 return E;
John McCallf89e55a2010-11-18 06:31:45 +000067}
68
John McCall120d63c2010-08-24 20:38:10 +000069static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
70 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +000071 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +000072 bool CStyle,
73 bool AllowObjCWritebackConversion);
Sam Panzerd0125862012-08-16 02:38:47 +000074
Fariborz Jahaniand97f5582011-03-23 19:50:54 +000075static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
76 QualType &ToType,
77 bool InOverloadResolution,
78 StandardConversionSequence &SCS,
79 bool CStyle);
John McCall120d63c2010-08-24 20:38:10 +000080static OverloadingResult
81IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
82 UserDefinedConversionSequence& User,
83 OverloadCandidateSet& Conversions,
84 bool AllowExplicit);
85
86
87static ImplicitConversionSequence::CompareKind
88CompareStandardConversionSequences(Sema &S,
89 const StandardConversionSequence& SCS1,
90 const StandardConversionSequence& SCS2);
91
92static ImplicitConversionSequence::CompareKind
93CompareQualificationConversions(Sema &S,
94 const StandardConversionSequence& SCS1,
95 const StandardConversionSequence& SCS2);
96
97static ImplicitConversionSequence::CompareKind
98CompareDerivedToBaseConversions(Sema &S,
99 const StandardConversionSequence& SCS1,
100 const StandardConversionSequence& SCS2);
101
102
103
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000104/// GetConversionCategory - Retrieve the implicit conversion
105/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +0000106ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000107GetConversionCategory(ImplicitConversionKind Kind) {
108 static const ImplicitConversionCategory
109 Category[(int)ICK_Num_Conversion_Kinds] = {
110 ICC_Identity,
111 ICC_Lvalue_Transformation,
112 ICC_Lvalue_Transformation,
113 ICC_Lvalue_Transformation,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000114 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000115 ICC_Qualification_Adjustment,
116 ICC_Promotion,
117 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000118 ICC_Promotion,
119 ICC_Conversion,
120 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000121 ICC_Conversion,
122 ICC_Conversion,
123 ICC_Conversion,
124 ICC_Conversion,
125 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000126 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000127 ICC_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000128 ICC_Conversion,
129 ICC_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000130 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000131 ICC_Conversion
132 };
133 return Category[(int)Kind];
134}
135
136/// GetConversionRank - Retrieve the implicit conversion rank
137/// corresponding to the given implicit conversion kind.
138ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
139 static const ImplicitConversionRank
140 Rank[(int)ICK_Num_Conversion_Kinds] = {
141 ICR_Exact_Match,
142 ICR_Exact_Match,
143 ICR_Exact_Match,
144 ICR_Exact_Match,
145 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000146 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000147 ICR_Promotion,
148 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000149 ICR_Promotion,
150 ICR_Conversion,
151 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000152 ICR_Conversion,
153 ICR_Conversion,
154 ICR_Conversion,
155 ICR_Conversion,
156 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000157 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000158 ICR_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000159 ICR_Conversion,
160 ICR_Conversion,
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000161 ICR_Complex_Real_Conversion,
162 ICR_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000163 ICR_Conversion,
164 ICR_Writeback_Conversion
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000165 };
166 return Rank[(int)Kind];
167}
168
169/// GetImplicitConversionName - Return the name of this kind of
170/// implicit conversion.
171const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +0000172 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000173 "No conversion",
174 "Lvalue-to-rvalue",
175 "Array-to-pointer",
176 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +0000177 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000178 "Qualification",
179 "Integral promotion",
180 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000181 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000182 "Integral conversion",
183 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000184 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000185 "Floating-integral conversion",
186 "Pointer conversion",
187 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000188 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000189 "Compatible-types conversion",
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000190 "Derived-to-base conversion",
191 "Vector conversion",
192 "Vector splat",
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000193 "Complex-real conversion",
194 "Block Pointer conversion",
195 "Transparent Union Conversion"
John McCallf85e1932011-06-15 23:02:42 +0000196 "Writeback conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000197 };
198 return Name[Kind];
199}
200
Douglas Gregor60d62c22008-10-31 16:23:19 +0000201/// StandardConversionSequence - Set the standard conversion
202/// sequence to the identity conversion.
203void StandardConversionSequence::setAsIdentityConversion() {
204 First = ICK_Identity;
205 Second = ICK_Identity;
206 Third = ICK_Identity;
Douglas Gregora9bff302010-02-28 18:30:25 +0000207 DeprecatedStringLiteralToCharPtr = false;
John McCallf85e1932011-06-15 23:02:42 +0000208 QualificationIncludesObjCLifetime = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000209 ReferenceBinding = false;
210 DirectBinding = false;
Douglas Gregor440a4832011-01-26 14:52:12 +0000211 IsLvalueReference = true;
212 BindsToFunctionLvalue = false;
213 BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +0000214 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +0000215 ObjCLifetimeConversionBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000216 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000217}
218
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000219/// getRank - Retrieve the rank of this standard conversion sequence
220/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
221/// implicit conversions.
222ImplicitConversionRank StandardConversionSequence::getRank() const {
223 ImplicitConversionRank Rank = ICR_Exact_Match;
224 if (GetConversionRank(First) > Rank)
225 Rank = GetConversionRank(First);
226 if (GetConversionRank(Second) > Rank)
227 Rank = GetConversionRank(Second);
228 if (GetConversionRank(Third) > Rank)
229 Rank = GetConversionRank(Third);
230 return Rank;
231}
232
233/// isPointerConversionToBool - Determines whether this conversion is
234/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000235/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000236/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000237bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000238 // Note that FromType has not necessarily been transformed by the
239 // array-to-pointer or function-to-pointer implicit conversions, so
240 // check for their presence as well as checking whether FromType is
241 // a pointer.
Douglas Gregorad323a82010-01-27 03:51:04 +0000242 if (getToType(1)->isBooleanType() &&
John McCallddb0ce72010-06-11 10:04:22 +0000243 (getFromType()->isPointerType() ||
244 getFromType()->isObjCObjectPointerType() ||
245 getFromType()->isBlockPointerType() ||
Anders Carlssonc8df0b62010-11-05 00:12:09 +0000246 getFromType()->isNullPtrType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000247 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
248 return true;
249
250 return false;
251}
252
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000253/// isPointerConversionToVoidPointer - Determines whether this
254/// conversion is a conversion of a pointer to a void pointer. This is
255/// used as part of the ranking of standard conversion sequences (C++
256/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000257bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000258StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000259isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000260 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000261 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000262
263 // Note that FromType has not necessarily been transformed by the
264 // array-to-pointer implicit conversion, so check for its presence
265 // and redo the conversion to get a pointer.
266 if (First == ICK_Array_To_Pointer)
267 FromType = Context.getArrayDecayedType(FromType);
268
Douglas Gregorf9af5242011-04-15 20:45:44 +0000269 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000270 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000271 return ToPtrType->getPointeeType()->isVoidType();
272
273 return false;
274}
275
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000276/// Skip any implicit casts which could be either part of a narrowing conversion
277/// or after one in an implicit conversion.
278static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
279 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
280 switch (ICE->getCastKind()) {
281 case CK_NoOp:
282 case CK_IntegralCast:
283 case CK_IntegralToBoolean:
284 case CK_IntegralToFloating:
285 case CK_FloatingToIntegral:
286 case CK_FloatingToBoolean:
287 case CK_FloatingCast:
288 Converted = ICE->getSubExpr();
289 continue;
290
291 default:
292 return Converted;
293 }
294 }
295
296 return Converted;
297}
298
299/// Check if this standard conversion sequence represents a narrowing
300/// conversion, according to C++11 [dcl.init.list]p7.
301///
302/// \param Ctx The AST context.
303/// \param Converted The result of applying this standard conversion sequence.
304/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
305/// value of the expression prior to the narrowing conversion.
Richard Smithf6028062012-03-23 23:55:39 +0000306/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
307/// type of the expression prior to the narrowing conversion.
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000308NarrowingKind
Richard Smith8ef7b202012-01-18 23:55:52 +0000309StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
310 const Expr *Converted,
Richard Smithf6028062012-03-23 23:55:39 +0000311 APValue &ConstantValue,
312 QualType &ConstantType) const {
David Blaikie4e4d0842012-03-11 07:00:24 +0000313 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000314
315 // C++11 [dcl.init.list]p7:
316 // A narrowing conversion is an implicit conversion ...
317 QualType FromType = getToType(0);
318 QualType ToType = getToType(1);
319 switch (Second) {
320 // -- from a floating-point type to an integer type, or
321 //
322 // -- from an integer type or unscoped enumeration type to a floating-point
323 // type, except where the source is a constant expression and the actual
324 // value after conversion will fit into the target type and will produce
325 // the original value when converted back to the original type, or
326 case ICK_Floating_Integral:
327 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
328 return NK_Type_Narrowing;
329 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
330 llvm::APSInt IntConstantValue;
331 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
332 if (Initializer &&
333 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
334 // Convert the integer to the floating type.
335 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
336 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
337 llvm::APFloat::rmNearestTiesToEven);
338 // And back.
339 llvm::APSInt ConvertedValue = IntConstantValue;
340 bool ignored;
341 Result.convertToInteger(ConvertedValue,
342 llvm::APFloat::rmTowardZero, &ignored);
343 // If the resulting value is different, this was a narrowing conversion.
344 if (IntConstantValue != ConvertedValue) {
345 ConstantValue = APValue(IntConstantValue);
Richard Smithf6028062012-03-23 23:55:39 +0000346 ConstantType = Initializer->getType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000347 return NK_Constant_Narrowing;
348 }
349 } else {
350 // Variables are always narrowings.
351 return NK_Variable_Narrowing;
352 }
353 }
354 return NK_Not_Narrowing;
355
356 // -- from long double to double or float, or from double to float, except
357 // where the source is a constant expression and the actual value after
358 // conversion is within the range of values that can be represented (even
359 // if it cannot be represented exactly), or
360 case ICK_Floating_Conversion:
361 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
362 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
363 // FromType is larger than ToType.
364 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
365 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
366 // Constant!
367 assert(ConstantValue.isFloat());
368 llvm::APFloat FloatVal = ConstantValue.getFloat();
369 // Convert the source value into the target type.
370 bool ignored;
371 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
372 Ctx.getFloatTypeSemantics(ToType),
373 llvm::APFloat::rmNearestTiesToEven, &ignored);
374 // If there was no overflow, the source value is within the range of
375 // values that can be represented.
Richard Smithf6028062012-03-23 23:55:39 +0000376 if (ConvertStatus & llvm::APFloat::opOverflow) {
377 ConstantType = Initializer->getType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000378 return NK_Constant_Narrowing;
Richard Smithf6028062012-03-23 23:55:39 +0000379 }
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000380 } else {
381 return NK_Variable_Narrowing;
382 }
383 }
384 return NK_Not_Narrowing;
385
386 // -- from an integer type or unscoped enumeration type to an integer type
387 // that cannot represent all the values of the original type, except where
388 // the source is a constant expression and the actual value after
389 // conversion will fit into the target type and will produce the original
390 // value when converted back to the original type.
391 case ICK_Boolean_Conversion: // Bools are integers too.
392 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
393 // Boolean conversions can be from pointers and pointers to members
394 // [conv.bool], and those aren't considered narrowing conversions.
395 return NK_Not_Narrowing;
396 } // Otherwise, fall through to the integral case.
397 case ICK_Integral_Conversion: {
398 assert(FromType->isIntegralOrUnscopedEnumerationType());
399 assert(ToType->isIntegralOrUnscopedEnumerationType());
400 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
401 const unsigned FromWidth = Ctx.getIntWidth(FromType);
402 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
403 const unsigned ToWidth = Ctx.getIntWidth(ToType);
404
405 if (FromWidth > ToWidth ||
Richard Smithcd65f492012-06-13 01:07:41 +0000406 (FromWidth == ToWidth && FromSigned != ToSigned) ||
407 (FromSigned && !ToSigned)) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000408 // Not all values of FromType can be represented in ToType.
409 llvm::APSInt InitializerValue;
410 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smithcd65f492012-06-13 01:07:41 +0000411 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
412 // Such conversions on variables are always narrowing.
413 return NK_Variable_Narrowing;
Richard Smith5d7700e2012-06-19 21:28:35 +0000414 }
415 bool Narrowing = false;
416 if (FromWidth < ToWidth) {
Richard Smithcd65f492012-06-13 01:07:41 +0000417 // Negative -> unsigned is narrowing. Otherwise, more bits is never
418 // narrowing.
419 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith5d7700e2012-06-19 21:28:35 +0000420 Narrowing = true;
Richard Smithcd65f492012-06-13 01:07:41 +0000421 } else {
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000422 // Add a bit to the InitializerValue so we don't have to worry about
423 // signed vs. unsigned comparisons.
424 InitializerValue = InitializerValue.extend(
425 InitializerValue.getBitWidth() + 1);
426 // Convert the initializer to and from the target width and signed-ness.
427 llvm::APSInt ConvertedValue = InitializerValue;
428 ConvertedValue = ConvertedValue.trunc(ToWidth);
429 ConvertedValue.setIsSigned(ToSigned);
430 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
431 ConvertedValue.setIsSigned(InitializerValue.isSigned());
432 // If the result is different, this was a narrowing conversion.
Richard Smith5d7700e2012-06-19 21:28:35 +0000433 if (ConvertedValue != InitializerValue)
434 Narrowing = true;
435 }
436 if (Narrowing) {
437 ConstantType = Initializer->getType();
438 ConstantValue = APValue(InitializerValue);
439 return NK_Constant_Narrowing;
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000440 }
441 }
442 return NK_Not_Narrowing;
443 }
444
445 default:
446 // Other kinds of conversions are not narrowings.
447 return NK_Not_Narrowing;
448 }
449}
450
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000451/// DebugPrint - Print this standard conversion sequence to standard
452/// error. Useful for debugging overloading issues.
453void StandardConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000454 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000455 bool PrintedSomething = false;
456 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000457 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000458 PrintedSomething = true;
459 }
460
461 if (Second != ICK_Identity) {
462 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000463 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000464 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000465 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000466
467 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000468 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000469 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000470 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000471 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000472 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000473 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000474 PrintedSomething = true;
475 }
476
477 if (Third != ICK_Identity) {
478 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000479 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000480 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000481 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000482 PrintedSomething = true;
483 }
484
485 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000486 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000487 }
488}
489
490/// DebugPrint - Print this user-defined conversion sequence to standard
491/// error. Useful for debugging overloading issues.
492void UserDefinedConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000493 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000494 if (Before.First || Before.Second || Before.Third) {
495 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000496 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000497 }
Sebastian Redlcc7a6482011-11-01 15:53:09 +0000498 if (ConversionFunction)
499 OS << '\'' << *ConversionFunction << '\'';
500 else
501 OS << "aggregate initialization";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000502 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000503 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000504 After.DebugPrint();
505 }
506}
507
508/// DebugPrint - Print this implicit conversion sequence to standard
509/// error. Useful for debugging overloading issues.
510void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000511 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000512 switch (ConversionKind) {
513 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000514 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000515 Standard.DebugPrint();
516 break;
517 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000518 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000519 UserDefined.DebugPrint();
520 break;
521 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000522 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000523 break;
John McCall1d318332010-01-12 00:44:57 +0000524 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000525 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000526 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000527 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000528 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000529 break;
530 }
531
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000532 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000533}
534
John McCall1d318332010-01-12 00:44:57 +0000535void AmbiguousConversionSequence::construct() {
536 new (&conversions()) ConversionSet();
537}
538
539void AmbiguousConversionSequence::destruct() {
540 conversions().~ConversionSet();
541}
542
543void
544AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
545 FromTypePtr = O.FromTypePtr;
546 ToTypePtr = O.ToTypePtr;
547 new (&conversions()) ConversionSet(O.conversions());
548}
549
Douglas Gregora9333192010-05-08 17:41:32 +0000550namespace {
Larisse Voufo43847122013-07-19 23:00:19 +0000551 // Structure used by DeductionFailureInfo to store
Richard Smith29805ca2013-01-31 05:19:49 +0000552 // template argument information.
553 struct DFIArguments {
Douglas Gregora9333192010-05-08 17:41:32 +0000554 TemplateArgument FirstArg;
555 TemplateArgument SecondArg;
556 };
Larisse Voufo43847122013-07-19 23:00:19 +0000557 // Structure used by DeductionFailureInfo to store
Richard Smith29805ca2013-01-31 05:19:49 +0000558 // template parameter and template argument information.
559 struct DFIParamWithArguments : DFIArguments {
560 TemplateParameter Param;
561 };
Douglas Gregora9333192010-05-08 17:41:32 +0000562}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000563
Douglas Gregora9333192010-05-08 17:41:32 +0000564/// \brief Convert from Sema's representation of template deduction information
565/// to the form used in overload-candidate information.
Larisse Voufo43847122013-07-19 23:00:19 +0000566DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context,
567 Sema::TemplateDeductionResult TDK,
568 TemplateDeductionInfo &Info) {
569 DeductionFailureInfo Result;
Douglas Gregora9333192010-05-08 17:41:32 +0000570 Result.Result = static_cast<unsigned>(TDK);
Richard Smithb8590f32012-05-07 09:03:25 +0000571 Result.HasDiagnostic = false;
Douglas Gregora9333192010-05-08 17:41:32 +0000572 Result.Data = 0;
573 switch (TDK) {
574 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000575 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000576 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000577 case Sema::TDK_TooManyArguments:
578 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000579 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000580
Douglas Gregora9333192010-05-08 17:41:32 +0000581 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000582 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000583 Result.Data = Info.Param.getOpaqueValue();
584 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000585
Richard Smith29805ca2013-01-31 05:19:49 +0000586 case Sema::TDK_NonDeducedMismatch: {
587 // FIXME: Should allocate from normal heap so that we can free this later.
588 DFIArguments *Saved = new (Context) DFIArguments;
589 Saved->FirstArg = Info.FirstArg;
590 Saved->SecondArg = Info.SecondArg;
591 Result.Data = Saved;
592 break;
593 }
594
Douglas Gregora9333192010-05-08 17:41:32 +0000595 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000596 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000597 // FIXME: Should allocate from normal heap so that we can free this later.
598 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000599 Saved->Param = Info.Param;
600 Saved->FirstArg = Info.FirstArg;
601 Saved->SecondArg = Info.SecondArg;
602 Result.Data = Saved;
603 break;
604 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000605
Douglas Gregora9333192010-05-08 17:41:32 +0000606 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000607 Result.Data = Info.take();
Richard Smithb8590f32012-05-07 09:03:25 +0000608 if (Info.hasSFINAEDiagnostic()) {
609 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
610 SourceLocation(), PartialDiagnostic::NullDiagnostic());
611 Info.takeSFINAEDiagnostic(*Diag);
612 Result.HasDiagnostic = true;
613 }
Douglas Gregorec20f462010-05-08 20:07:26 +0000614 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000615
Douglas Gregora9333192010-05-08 17:41:32 +0000616 case Sema::TDK_FailedOverloadResolution:
Richard Smith0efa62f2013-01-31 04:03:12 +0000617 Result.Data = Info.Expression;
618 break;
619
Richard Smith29805ca2013-01-31 05:19:49 +0000620 case Sema::TDK_MiscellaneousDeductionFailure:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000621 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000622 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000623
Douglas Gregora9333192010-05-08 17:41:32 +0000624 return Result;
625}
John McCall1d318332010-01-12 00:44:57 +0000626
Larisse Voufo43847122013-07-19 23:00:19 +0000627void DeductionFailureInfo::Destroy() {
Douglas Gregora9333192010-05-08 17:41:32 +0000628 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
629 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000630 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000631 case Sema::TDK_InstantiationDepth:
632 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000633 case Sema::TDK_TooManyArguments:
634 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000635 case Sema::TDK_InvalidExplicitArguments:
Richard Smith29805ca2013-01-31 05:19:49 +0000636 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000637 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000638
Douglas Gregora9333192010-05-08 17:41:32 +0000639 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000640 case Sema::TDK_Underqualified:
Richard Smith29805ca2013-01-31 05:19:49 +0000641 case Sema::TDK_NonDeducedMismatch:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000642 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000643 Data = 0;
644 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000645
646 case Sema::TDK_SubstitutionFailure:
Richard Smithb8590f32012-05-07 09:03:25 +0000647 // FIXME: Destroy the template argument list?
Douglas Gregorec20f462010-05-08 20:07:26 +0000648 Data = 0;
Richard Smithb8590f32012-05-07 09:03:25 +0000649 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
650 Diag->~PartialDiagnosticAt();
651 HasDiagnostic = false;
652 }
Douglas Gregorec20f462010-05-08 20:07:26 +0000653 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000654
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000655 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000656 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000657 break;
658 }
659}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000660
Larisse Voufo43847122013-07-19 23:00:19 +0000661PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smithb8590f32012-05-07 09:03:25 +0000662 if (HasDiagnostic)
663 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
664 return 0;
665}
666
Larisse Voufo43847122013-07-19 23:00:19 +0000667TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregora9333192010-05-08 17:41:32 +0000668 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
669 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000670 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000671 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000672 case Sema::TDK_TooManyArguments:
673 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000674 case Sema::TDK_SubstitutionFailure:
Richard Smith29805ca2013-01-31 05:19:49 +0000675 case Sema::TDK_NonDeducedMismatch:
676 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000677 return TemplateParameter();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000678
Douglas Gregora9333192010-05-08 17:41:32 +0000679 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000680 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000681 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregora9333192010-05-08 17:41:32 +0000682
683 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000684 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000685 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000686
Douglas Gregora9333192010-05-08 17:41:32 +0000687 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000688 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000689 break;
690 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000691
Douglas Gregora9333192010-05-08 17:41:32 +0000692 return TemplateParameter();
693}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000694
Larisse Voufo43847122013-07-19 23:00:19 +0000695TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregorec20f462010-05-08 20:07:26 +0000696 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith29805ca2013-01-31 05:19:49 +0000697 case Sema::TDK_Success:
698 case Sema::TDK_Invalid:
699 case Sema::TDK_InstantiationDepth:
700 case Sema::TDK_TooManyArguments:
701 case Sema::TDK_TooFewArguments:
702 case Sema::TDK_Incomplete:
703 case Sema::TDK_InvalidExplicitArguments:
704 case Sema::TDK_Inconsistent:
705 case Sema::TDK_Underqualified:
706 case Sema::TDK_NonDeducedMismatch:
707 case Sema::TDK_FailedOverloadResolution:
708 return 0;
Douglas Gregorec20f462010-05-08 20:07:26 +0000709
Richard Smith29805ca2013-01-31 05:19:49 +0000710 case Sema::TDK_SubstitutionFailure:
711 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000712
Richard Smith29805ca2013-01-31 05:19:49 +0000713 // Unhandled
714 case Sema::TDK_MiscellaneousDeductionFailure:
715 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000716 }
717
718 return 0;
719}
720
Larisse Voufo43847122013-07-19 23:00:19 +0000721const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregora9333192010-05-08 17:41:32 +0000722 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
723 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000724 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000725 case Sema::TDK_InstantiationDepth:
726 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000727 case Sema::TDK_TooManyArguments:
728 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000729 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000730 case Sema::TDK_SubstitutionFailure:
Richard Smith29805ca2013-01-31 05:19:49 +0000731 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000732 return 0;
733
Douglas Gregora9333192010-05-08 17:41:32 +0000734 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000735 case Sema::TDK_Underqualified:
Richard Smith29805ca2013-01-31 05:19:49 +0000736 case Sema::TDK_NonDeducedMismatch:
737 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000738
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000739 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000740 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000741 break;
742 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000743
Douglas Gregora9333192010-05-08 17:41:32 +0000744 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000745}
Douglas Gregora9333192010-05-08 17:41:32 +0000746
Larisse Voufo43847122013-07-19 23:00:19 +0000747const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregora9333192010-05-08 17:41:32 +0000748 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
749 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000750 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000751 case Sema::TDK_InstantiationDepth:
752 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000753 case Sema::TDK_TooManyArguments:
754 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000755 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000756 case Sema::TDK_SubstitutionFailure:
Richard Smith29805ca2013-01-31 05:19:49 +0000757 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000758 return 0;
759
Douglas Gregora9333192010-05-08 17:41:32 +0000760 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000761 case Sema::TDK_Underqualified:
Richard Smith29805ca2013-01-31 05:19:49 +0000762 case Sema::TDK_NonDeducedMismatch:
763 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000764
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000765 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000766 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000767 break;
768 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000769
Douglas Gregora9333192010-05-08 17:41:32 +0000770 return 0;
771}
772
Larisse Voufo43847122013-07-19 23:00:19 +0000773Expr *DeductionFailureInfo::getExpr() {
Richard Smith0efa62f2013-01-31 04:03:12 +0000774 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
775 Sema::TDK_FailedOverloadResolution)
776 return static_cast<Expr*>(Data);
777
778 return 0;
779}
780
Benjamin Kramerf5b132f2012-10-09 15:52:25 +0000781void OverloadCandidateSet::destroyCandidates() {
Richard Smithe3898ac2012-07-18 23:52:59 +0000782 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer9e2822b2012-01-14 20:16:52 +0000783 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
784 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smithe3898ac2012-07-18 23:52:59 +0000785 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
786 i->DeductionFailure.Destroy();
787 }
Benjamin Kramerf5b132f2012-10-09 15:52:25 +0000788}
789
790void OverloadCandidateSet::clear() {
791 destroyCandidates();
Benjamin Kramer314f5542012-01-14 19:31:39 +0000792 NumInlineSequences = 0;
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +0000793 Candidates.clear();
Douglas Gregora9333192010-05-08 17:41:32 +0000794 Functions.clear();
795}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000796
John McCall5acb0c92011-10-17 18:40:02 +0000797namespace {
798 class UnbridgedCastsSet {
799 struct Entry {
800 Expr **Addr;
801 Expr *Saved;
802 };
803 SmallVector<Entry, 2> Entries;
804
805 public:
806 void save(Sema &S, Expr *&E) {
807 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
808 Entry entry = { &E, E };
809 Entries.push_back(entry);
810 E = S.stripARCUnbridgedCast(E);
811 }
812
813 void restore() {
814 for (SmallVectorImpl<Entry>::iterator
815 i = Entries.begin(), e = Entries.end(); i != e; ++i)
816 *i->Addr = i->Saved;
817 }
818 };
819}
820
821/// checkPlaceholderForOverload - Do any interesting placeholder-like
822/// preprocessing on the given expression.
823///
824/// \param unbridgedCasts a collection to which to add unbridged casts;
825/// without this, they will be immediately diagnosed as errors
826///
827/// Return true on unrecoverable error.
828static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
829 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall5acb0c92011-10-17 18:40:02 +0000830 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
831 // We can't handle overloaded expressions here because overload
832 // resolution might reasonably tweak them.
833 if (placeholder->getKind() == BuiltinType::Overload) return false;
834
835 // If the context potentially accepts unbridged ARC casts, strip
836 // the unbridged cast and add it to the collection for later restoration.
837 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
838 unbridgedCasts) {
839 unbridgedCasts->save(S, E);
840 return false;
841 }
842
843 // Go ahead and check everything else.
844 ExprResult result = S.CheckPlaceholderExpr(E);
845 if (result.isInvalid())
846 return true;
847
848 E = result.take();
849 return false;
850 }
851
852 // Nothing to do.
853 return false;
854}
855
856/// checkArgPlaceholdersForOverload - Check a set of call operands for
857/// placeholders.
Dmitri Gribenko9e00f122013-05-09 21:02:07 +0000858static bool checkArgPlaceholdersForOverload(Sema &S,
859 MultiExprArg Args,
John McCall5acb0c92011-10-17 18:40:02 +0000860 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9e00f122013-05-09 21:02:07 +0000861 for (unsigned i = 0, e = Args.size(); i != e; ++i)
862 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall5acb0c92011-10-17 18:40:02 +0000863 return true;
864
865 return false;
866}
867
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000868// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000869// overload of the declarations in Old. This routine returns false if
870// New and Old cannot be overloaded, e.g., if New has the same
871// signature as some function in Old (C++ 1.3.10) or if the Old
872// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000873// it does return false, MatchedDecl will point to the decl that New
874// cannot be overloaded with. This decl may be a UsingShadowDecl on
875// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000876//
877// Example: Given the following input:
878//
879// void f(int, float); // #1
880// void f(int, int); // #2
881// int f(int, int); // #3
882//
883// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000884// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000885//
John McCall51fa86f2009-12-02 08:47:38 +0000886// When we process #2, Old contains only the FunctionDecl for #1. By
887// comparing the parameter types, we see that #1 and #2 are overloaded
888// (since they have different signatures), so this routine returns
889// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000890//
John McCall51fa86f2009-12-02 08:47:38 +0000891// When we process #3, Old is an overload set containing #1 and #2. We
892// compare the signatures of #3 to #1 (they're overloaded, so we do
893// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
894// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000895// signature), IsOverload returns false and MatchedDecl will be set to
896// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000897//
898// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
899// into a class by a using declaration. The rules for whether to hide
900// shadow declarations ignore some properties which otherwise figure
901// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000902Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000903Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
904 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000905 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000906 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000907 NamedDecl *OldD = *I;
908
909 bool OldIsUsingDecl = false;
910 if (isa<UsingShadowDecl>(OldD)) {
911 OldIsUsingDecl = true;
912
913 // We can always introduce two using declarations into the same
914 // context, even if they have identical signatures.
915 if (NewIsUsingDecl) continue;
916
917 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
918 }
919
920 // If either declaration was introduced by a using declaration,
921 // we'll need to use slightly different rules for matching.
922 // Essentially, these rules are the normal rules, except that
923 // function templates hide function templates with different
924 // return types or template parameter lists.
925 bool UseMemberUsingDeclRules =
John McCall78037ac2013-04-03 21:19:47 +0000926 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
927 !New->getFriendObjectKind();
John McCallad00b772010-06-16 08:42:20 +0000928
John McCall51fa86f2009-12-02 08:47:38 +0000929 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000930 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
931 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
932 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
933 continue;
934 }
935
John McCall871b2e72009-12-09 03:35:25 +0000936 Match = *I;
937 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000938 }
John McCall51fa86f2009-12-02 08:47:38 +0000939 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000940 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
941 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
942 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
943 continue;
944 }
945
Rafael Espindola90cc3902013-04-15 12:49:13 +0000946 if (!shouldLinkPossiblyHiddenDecl(*I, New))
947 continue;
948
John McCall871b2e72009-12-09 03:35:25 +0000949 Match = *I;
950 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000951 }
John McCalld7945c62010-11-10 03:01:53 +0000952 } else if (isa<UsingDecl>(OldD)) {
John McCall9f54ad42009-12-10 09:41:52 +0000953 // We can overload with these, which can show up when doing
954 // redeclaration checks for UsingDecls.
955 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalld7945c62010-11-10 03:01:53 +0000956 } else if (isa<TagDecl>(OldD)) {
957 // We can always overload with tags by hiding them.
John McCall9f54ad42009-12-10 09:41:52 +0000958 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
959 // Optimistically assume that an unresolved using decl will
960 // overload; if it doesn't, we'll have to diagnose during
961 // template instantiation.
962 } else {
John McCall68263142009-11-18 22:49:29 +0000963 // (C++ 13p1):
964 // Only function declarations can be overloaded; object and type
965 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000966 Match = *I;
967 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000968 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000969 }
John McCall68263142009-11-18 22:49:29 +0000970
John McCall871b2e72009-12-09 03:35:25 +0000971 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000972}
973
Richard Smithaa4bc182013-06-30 09:48:50 +0000974bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
975 bool UseUsingDeclRules) {
976 // C++ [basic.start.main]p2: This function shall not be overloaded.
977 if (New->isMain())
Rafael Espindola78eeba82012-12-28 14:21:58 +0000978 return false;
Rafael Espindola7a525ac2013-01-12 01:47:40 +0000979
John McCall68263142009-11-18 22:49:29 +0000980 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
981 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
982
983 // C++ [temp.fct]p2:
984 // A function template can be overloaded with other function templates
985 // and with normal (non-template) functions.
986 if ((OldTemplate == 0) != (NewTemplate == 0))
987 return true;
988
989 // Is the function New an overload of the function Old?
Richard Smithaa4bc182013-06-30 09:48:50 +0000990 QualType OldQType = Context.getCanonicalType(Old->getType());
991 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall68263142009-11-18 22:49:29 +0000992
993 // Compare the signatures (C++ 1.3.10) of the two functions to
994 // determine whether they are overloads. If we find any mismatch
995 // in the signature, they are overloads.
996
997 // If either of these functions is a K&R-style function (no
998 // prototype), then we consider them to have matching signatures.
999 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1000 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1001 return false;
1002
John McCallf4c73712011-01-19 06:33:43 +00001003 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
1004 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall68263142009-11-18 22:49:29 +00001005
1006 // The signature of a function includes the types of its
1007 // parameters (C++ 1.3.10), which includes the presence or absence
1008 // of the ellipsis; see C++ DR 357).
1009 if (OldQType != NewQType &&
1010 (OldType->getNumArgs() != NewType->getNumArgs() ||
1011 OldType->isVariadic() != NewType->isVariadic() ||
Richard Smithaa4bc182013-06-30 09:48:50 +00001012 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +00001013 return true;
1014
1015 // C++ [temp.over.link]p4:
1016 // The signature of a function template consists of its function
1017 // signature, its return type and its template parameter list. The names
1018 // of the template parameters are significant only for establishing the
1019 // relationship between the template parameters and the rest of the
1020 // signature.
1021 //
1022 // We check the return type and template parameter lists for function
1023 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +00001024 //
1025 // However, we don't consider either of these when deciding whether
1026 // a member introduced by a shadow declaration is hidden.
1027 if (!UseUsingDeclRules && NewTemplate &&
Richard Smithaa4bc182013-06-30 09:48:50 +00001028 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1029 OldTemplate->getTemplateParameters(),
1030 false, TPL_TemplateMatch) ||
John McCall68263142009-11-18 22:49:29 +00001031 OldType->getResultType() != NewType->getResultType()))
1032 return true;
1033
1034 // If the function is a class member, its signature includes the
Douglas Gregor57c9f4f2011-01-26 17:47:49 +00001035 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall68263142009-11-18 22:49:29 +00001036 //
1037 // As part of this, also check whether one of the member functions
1038 // is static, in which case they are not overloads (C++
1039 // 13.1p2). While not part of the definition of the signature,
1040 // this check is important to determine whether these functions
1041 // can be overloaded.
Richard Smith21c8fa82013-01-14 05:37:29 +00001042 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1043 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall68263142009-11-18 22:49:29 +00001044 if (OldMethod && NewMethod &&
Richard Smith21c8fa82013-01-14 05:37:29 +00001045 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1046 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1047 if (!UseUsingDeclRules &&
1048 (OldMethod->getRefQualifier() == RQ_None ||
1049 NewMethod->getRefQualifier() == RQ_None)) {
1050 // C++0x [over.load]p2:
1051 // - Member function declarations with the same name and the same
1052 // parameter-type-list as well as member function template
1053 // declarations with the same name, the same parameter-type-list, and
1054 // the same template parameter lists cannot be overloaded if any of
1055 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithaa4bc182013-06-30 09:48:50 +00001056 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith21c8fa82013-01-14 05:37:29 +00001057 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithaa4bc182013-06-30 09:48:50 +00001058 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith21c8fa82013-01-14 05:37:29 +00001059 }
1060 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +00001061 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001062
Richard Smith21c8fa82013-01-14 05:37:29 +00001063 // We may not have applied the implicit const for a constexpr member
1064 // function yet (because we haven't yet resolved whether this is a static
1065 // or non-static member function). Add it now, on the assumption that this
1066 // is a redeclaration of OldMethod.
1067 unsigned NewQuals = NewMethod->getTypeQualifiers();
Richard Smithaa4bc182013-06-30 09:48:50 +00001068 if (!getLangOpts().CPlusPlus1y && NewMethod->isConstexpr() &&
Richard Smithdb2fe732013-06-25 18:46:26 +00001069 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith21c8fa82013-01-14 05:37:29 +00001070 NewQuals |= Qualifiers::Const;
1071 if (OldMethod->getTypeQualifiers() != NewQuals)
1072 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +00001073 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001074
John McCall68263142009-11-18 22:49:29 +00001075 // The signatures match; this is not an overload.
1076 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001077}
1078
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00001079/// \brief Checks availability of the function depending on the current
1080/// function context. Inside an unavailable function, unavailability is ignored.
1081///
1082/// \returns true if \arg FD is unavailable and current context is inside
1083/// an available function, false otherwise.
1084bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1085 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1086}
1087
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001088/// \brief Tries a user-defined conversion from From to ToType.
1089///
1090/// Produces an implicit conversion sequence for when a standard conversion
1091/// is not an option. See TryImplicitConversion for more information.
1092static ImplicitConversionSequence
1093TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1094 bool SuppressUserConversions,
1095 bool AllowExplicit,
1096 bool InOverloadResolution,
1097 bool CStyle,
1098 bool AllowObjCWritebackConversion) {
1099 ImplicitConversionSequence ICS;
1100
1101 if (SuppressUserConversions) {
1102 // We're not in the case above, so there is no conversion that
1103 // we can perform.
1104 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1105 return ICS;
1106 }
1107
1108 // Attempt user-defined conversion.
1109 OverloadCandidateSet Conversions(From->getExprLoc());
1110 OverloadingResult UserDefResult
1111 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1112 AllowExplicit);
1113
1114 if (UserDefResult == OR_Success) {
1115 ICS.setUserDefined();
1116 // C++ [over.ics.user]p4:
1117 // A conversion of an expression of class type to the same class
1118 // type is given Exact Match rank, and a conversion of an
1119 // expression of class type to a base class of that type is
1120 // given Conversion rank, in spite of the fact that a copy
1121 // constructor (i.e., a user-defined conversion function) is
1122 // called for those cases.
1123 if (CXXConstructorDecl *Constructor
1124 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1125 QualType FromCanon
1126 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1127 QualType ToCanon
1128 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1129 if (Constructor->isCopyConstructor() &&
1130 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1131 // Turn this into a "standard" conversion sequence, so that it
1132 // gets ranked with standard conversion sequences.
1133 ICS.setStandard();
1134 ICS.Standard.setAsIdentityConversion();
1135 ICS.Standard.setFromType(From->getType());
1136 ICS.Standard.setAllToTypes(ToType);
1137 ICS.Standard.CopyConstructor = Constructor;
1138 if (ToCanon != FromCanon)
1139 ICS.Standard.Second = ICK_Derived_To_Base;
1140 }
1141 }
1142
1143 // C++ [over.best.ics]p4:
1144 // However, when considering the argument of a user-defined
1145 // conversion function that is a candidate by 13.3.1.3 when
1146 // invoked for the copying of the temporary in the second step
1147 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1148 // 13.3.1.6 in all cases, only standard conversion sequences and
1149 // ellipsis conversion sequences are allowed.
1150 if (SuppressUserConversions && ICS.isUserDefined()) {
1151 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1152 }
1153 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1154 ICS.setAmbiguous();
1155 ICS.Ambiguous.setFromType(From->getType());
1156 ICS.Ambiguous.setToType(ToType);
1157 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1158 Cand != Conversions.end(); ++Cand)
1159 if (Cand->Viable)
1160 ICS.Ambiguous.addConversion(Cand->Function);
1161 } else {
1162 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1163 }
1164
1165 return ICS;
1166}
1167
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001168/// TryImplicitConversion - Attempt to perform an implicit conversion
1169/// from the given expression (Expr) to the given type (ToType). This
1170/// function returns an implicit conversion sequence that can be used
1171/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001172///
1173/// void f(float f);
1174/// void g(int i) { f(i); }
1175///
1176/// this routine would produce an implicit conversion sequence to
1177/// describe the initialization of f from i, which will be a standard
1178/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1179/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1180//
1181/// Note that this routine only determines how the conversion can be
1182/// performed; it does not actually perform the conversion. As such,
1183/// it will not produce any diagnostics if no conversion is available,
1184/// but will instead return an implicit conversion sequence of kind
1185/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +00001186///
1187/// If @p SuppressUserConversions, then user-defined conversions are
1188/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001189/// If @p AllowExplicit, then explicit user-defined conversions are
1190/// permitted.
John McCallf85e1932011-06-15 23:02:42 +00001191///
1192/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1193/// writeback conversion, which allows __autoreleasing id* parameters to
1194/// be initialized with __strong id* or __weak id* arguments.
John McCall120d63c2010-08-24 20:38:10 +00001195static ImplicitConversionSequence
1196TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1197 bool SuppressUserConversions,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001198 bool AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001199 bool InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001200 bool CStyle,
1201 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001202 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +00001203 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001204 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall1d318332010-01-12 00:44:57 +00001205 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +00001206 return ICS;
1207 }
1208
David Blaikie4e4d0842012-03-11 07:00:24 +00001209 if (!S.getLangOpts().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +00001210 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +00001211 return ICS;
1212 }
1213
Douglas Gregor604eb652010-08-11 02:15:33 +00001214 // C++ [over.ics.user]p4:
1215 // A conversion of an expression of class type to the same class
1216 // type is given Exact Match rank, and a conversion of an
1217 // expression of class type to a base class of that type is
1218 // given Conversion rank, in spite of the fact that a copy/move
1219 // constructor (i.e., a user-defined conversion function) is
1220 // called for those cases.
1221 QualType FromType = From->getType();
1222 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00001223 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1224 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001225 ICS.setStandard();
1226 ICS.Standard.setAsIdentityConversion();
1227 ICS.Standard.setFromType(FromType);
1228 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001229
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001230 // We don't actually check at this point whether there is a valid
1231 // copy/move constructor, since overloading just assumes that it
1232 // exists. When we actually perform initialization, we'll find the
1233 // appropriate constructor to copy the returned object, if needed.
1234 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001235
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001236 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +00001237 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001238 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001239
Douglas Gregor604eb652010-08-11 02:15:33 +00001240 return ICS;
1241 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001242
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001243 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1244 AllowExplicit, InOverloadResolution, CStyle,
1245 AllowObjCWritebackConversion);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001246}
1247
John McCallf85e1932011-06-15 23:02:42 +00001248ImplicitConversionSequence
1249Sema::TryImplicitConversion(Expr *From, QualType ToType,
1250 bool SuppressUserConversions,
1251 bool AllowExplicit,
1252 bool InOverloadResolution,
1253 bool CStyle,
1254 bool AllowObjCWritebackConversion) {
1255 return clang::TryImplicitConversion(*this, From, ToType,
1256 SuppressUserConversions, AllowExplicit,
1257 InOverloadResolution, CStyle,
1258 AllowObjCWritebackConversion);
John McCall120d63c2010-08-24 20:38:10 +00001259}
1260
Douglas Gregor575c63a2010-04-16 22:27:05 +00001261/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley429bb272011-04-08 18:41:53 +00001262/// expression From to the type ToType. Returns the
Douglas Gregor575c63a2010-04-16 22:27:05 +00001263/// converted expression. Flavor is the kind of conversion we're
1264/// performing, used in the error message. If @p AllowExplicit,
1265/// explicit user-defined conversions are permitted.
John Wiegley429bb272011-04-08 18:41:53 +00001266ExprResult
1267Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001268 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregor575c63a2010-04-16 22:27:05 +00001269 ImplicitConversionSequence ICS;
Sebastian Redl091fffe2011-10-16 18:19:06 +00001270 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001271}
1272
John Wiegley429bb272011-04-08 18:41:53 +00001273ExprResult
1274Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor575c63a2010-04-16 22:27:05 +00001275 AssignmentAction Action, bool AllowExplicit,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001276 ImplicitConversionSequence& ICS) {
John McCall3c3b7f92011-10-25 17:37:35 +00001277 if (checkPlaceholderForOverload(*this, From))
1278 return ExprError();
1279
John McCallf85e1932011-06-15 23:02:42 +00001280 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1281 bool AllowObjCWritebackConversion
David Blaikie4e4d0842012-03-11 07:00:24 +00001282 = getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001283 (Action == AA_Passing || Action == AA_Sending);
John McCallf85e1932011-06-15 23:02:42 +00001284
John McCall120d63c2010-08-24 20:38:10 +00001285 ICS = clang::TryImplicitConversion(*this, From, ToType,
1286 /*SuppressUserConversions=*/false,
1287 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001288 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00001289 /*CStyle=*/false,
1290 AllowObjCWritebackConversion);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001291 return PerformImplicitConversion(From, ToType, ICS, Action);
1292}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001293
1294/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor43c79c22009-12-09 00:47:37 +00001295/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth18e04612011-06-18 01:19:03 +00001296bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1297 QualType &ResultTy) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001298 if (Context.hasSameUnqualifiedType(FromType, ToType))
1299 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001300
John McCall00ccbef2010-12-21 00:44:39 +00001301 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1302 // where F adds one of the following at most once:
1303 // - a pointer
1304 // - a member pointer
1305 // - a block pointer
1306 CanQualType CanTo = Context.getCanonicalType(ToType);
1307 CanQualType CanFrom = Context.getCanonicalType(FromType);
1308 Type::TypeClass TyClass = CanTo->getTypeClass();
1309 if (TyClass != CanFrom->getTypeClass()) return false;
1310 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1311 if (TyClass == Type::Pointer) {
1312 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1313 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1314 } else if (TyClass == Type::BlockPointer) {
1315 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1316 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1317 } else if (TyClass == Type::MemberPointer) {
1318 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1319 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1320 } else {
1321 return false;
1322 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001323
John McCall00ccbef2010-12-21 00:44:39 +00001324 TyClass = CanTo->getTypeClass();
1325 if (TyClass != CanFrom->getTypeClass()) return false;
1326 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1327 return false;
1328 }
1329
1330 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1331 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1332 if (!EInfo.getNoReturn()) return false;
1333
1334 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1335 assert(QualType(FromFn, 0).isCanonical());
1336 if (QualType(FromFn, 0) != CanTo) return false;
1337
1338 ResultTy = ToType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001339 return true;
1340}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001341
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001342/// \brief Determine whether the conversion from FromType to ToType is a valid
1343/// vector conversion.
1344///
1345/// \param ICK Will be set to the vector conversion kind, if this is a vector
1346/// conversion.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001347static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1348 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001349 // We need at least one of these types to be a vector type to have a vector
1350 // conversion.
1351 if (!ToType->isVectorType() && !FromType->isVectorType())
1352 return false;
1353
1354 // Identical types require no conversions.
1355 if (Context.hasSameUnqualifiedType(FromType, ToType))
1356 return false;
1357
1358 // There are no conversions between extended vector types, only identity.
1359 if (ToType->isExtVectorType()) {
1360 // There are no conversions between extended vector types other than the
1361 // identity conversion.
1362 if (FromType->isExtVectorType())
1363 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001364
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001365 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +00001366 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001367 ICK = ICK_Vector_Splat;
1368 return true;
1369 }
1370 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001371
1372 // We can perform the conversion between vector types in the following cases:
1373 // 1)vector types are equivalent AltiVec and GCC vector types
1374 // 2)lax vector conversions are permitted and the vector types are of the
1375 // same size
1376 if (ToType->isVectorType() && FromType->isVectorType()) {
1377 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
David Blaikie4e4d0842012-03-11 07:00:24 +00001378 (Context.getLangOpts().LaxVectorConversions &&
Chandler Carruthc45eb9c2010-08-08 05:02:51 +00001379 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +00001380 ICK = ICK_Vector_Conversion;
1381 return true;
1382 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001383 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001384
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001385 return false;
1386}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001387
Douglas Gregor7d000652012-04-12 20:48:09 +00001388static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1389 bool InOverloadResolution,
1390 StandardConversionSequence &SCS,
1391 bool CStyle);
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001392
Douglas Gregor60d62c22008-10-31 16:23:19 +00001393/// IsStandardConversion - Determines whether there is a standard
1394/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1395/// expression From to the type ToType. Standard conversion sequences
1396/// only consider non-class types; for conversions that involve class
1397/// types, use TryImplicitConversion. If a conversion exists, SCS will
1398/// contain the standard conversion sequence required to perform this
1399/// conversion and this routine will return true. Otherwise, this
1400/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +00001401static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1402 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001403 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +00001404 bool CStyle,
1405 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001406 QualType FromType = From->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001407
Douglas Gregor60d62c22008-10-31 16:23:19 +00001408 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001409 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +00001410 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +00001411 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +00001412 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +00001413 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001414
Douglas Gregorf9201e02009-02-11 23:02:49 +00001415 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +00001416 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +00001417 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001418 if (S.getLangOpts().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001419 return false;
1420
Mike Stump1eb44332009-09-09 15:08:12 +00001421 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001422 }
1423
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001424 // The first conversion can be an lvalue-to-rvalue conversion,
1425 // array-to-pointer conversion, or function-to-pointer conversion
1426 // (C++ 4p1).
1427
John McCall120d63c2010-08-24 20:38:10 +00001428 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001429 DeclAccessPair AccessPair;
1430 if (FunctionDecl *Fn
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001431 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall120d63c2010-08-24 20:38:10 +00001432 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001433 // We were able to resolve the address of the overloaded function,
1434 // so we can convert to the type of that function.
1435 FromType = Fn->getType();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001436
1437 // we can sometimes resolve &foo<int> regardless of ToType, so check
1438 // if the type matches (identity) or we are converting to bool
1439 if (!S.Context.hasSameUnqualifiedType(
1440 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1441 QualType resultTy;
1442 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth18e04612011-06-18 01:19:03 +00001443 if (!S.IsNoReturnConversion(FromType,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001444 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1445 // otherwise, only a boolean conversion is standard
1446 if (!ToType->isBooleanType())
1447 return false;
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001448 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001449
Chandler Carruth90434232011-03-29 08:08:18 +00001450 // Check if the "from" expression is taking the address of an overloaded
1451 // function and recompute the FromType accordingly. Take advantage of the
1452 // fact that non-static member functions *must* have such an address-of
1453 // expression.
1454 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1455 if (Method && !Method->isStatic()) {
1456 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1457 "Non-unary operator on non-static member address");
1458 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1459 == UO_AddrOf &&
1460 "Non-address-of operator on non-static member address");
1461 const Type *ClassType
1462 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1463 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruthfc5c8fc2011-03-29 18:38:10 +00001464 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1465 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1466 UO_AddrOf &&
Chandler Carruth90434232011-03-29 08:08:18 +00001467 "Non-address-of operator for overloaded function expression");
1468 FromType = S.Context.getPointerType(FromType);
1469 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001470
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001471 // Check that we've computed the proper type after overload resolution.
Chandler Carruth90434232011-03-29 08:08:18 +00001472 assert(S.Context.hasSameType(
1473 FromType,
1474 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001475 } else {
1476 return false;
1477 }
Anders Carlsson2bd62502010-11-04 05:28:09 +00001478 }
John McCall21480112011-08-30 00:57:29 +00001479 // Lvalue-to-rvalue conversion (C++11 4.1):
1480 // A glvalue (3.10) of a non-function, non-array type T can
1481 // be converted to a prvalue.
1482 bool argIsLValue = From->isGLValue();
John McCall7eb0a9e2010-11-24 05:12:34 +00001483 if (argIsLValue &&
Douglas Gregor904eed32008-11-10 20:40:00 +00001484 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +00001485 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001486 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001487
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001488 // C11 6.3.2.1p2:
1489 // ... if the lvalue has atomic type, the value has the non-atomic version
1490 // of the type of the lvalue ...
1491 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1492 FromType = Atomic->getValueType();
1493
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001494 // If T is a non-class type, the type of the rvalue is the
1495 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001496 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1497 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001498 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001499 } else if (FromType->isArrayType()) {
1500 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001501 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001502
1503 // An lvalue or rvalue of type "array of N T" or "array of unknown
1504 // bound of T" can be converted to an rvalue of type "pointer to
1505 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001506 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001507
John McCall120d63c2010-08-24 20:38:10 +00001508 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001509 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001510 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001511
1512 // For the purpose of ranking in overload resolution
1513 // (13.3.3.1.1), this conversion is considered an
1514 // array-to-pointer conversion followed by a qualification
1515 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001516 SCS.Second = ICK_Identity;
1517 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001518 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregorad323a82010-01-27 03:51:04 +00001519 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001520 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001521 }
John McCall7eb0a9e2010-11-24 05:12:34 +00001522 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001523 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001524 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001525
1526 // An lvalue of function type T can be converted to an rvalue of
1527 // type "pointer to T." The result is a pointer to the
1528 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001529 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001530 } else {
1531 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001532 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001533 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001534 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001535
1536 // The second conversion can be an integral promotion, floating
1537 // point promotion, integral conversion, floating point conversion,
1538 // floating-integral conversion, pointer conversion,
1539 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001540 // For overloading in C, this can also be a "compatible-type"
1541 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001542 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001543 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001544 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001545 // The unqualified versions of the types are the same: there's no
1546 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001547 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001548 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001549 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001550 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001551 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001552 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001553 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001554 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001555 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001556 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001557 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001558 SCS.Second = ICK_Complex_Promotion;
1559 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001560 } else if (ToType->isBooleanType() &&
1561 (FromType->isArithmeticType() ||
1562 FromType->isAnyPointerType() ||
1563 FromType->isBlockPointerType() ||
1564 FromType->isMemberPointerType() ||
1565 FromType->isNullPtrType())) {
1566 // Boolean conversions (C++ 4.12).
1567 SCS.Second = ICK_Boolean_Conversion;
1568 FromType = S.Context.BoolTy;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001569 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001570 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001571 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001572 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001573 FromType = ToType.getUnqualifiedType();
Richard Smith42860f12013-05-10 20:29:50 +00001574 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001575 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001576 SCS.Second = ICK_Complex_Conversion;
1577 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001578 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1579 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001580 // Complex-real conversions (C99 6.3.1.7)
1581 SCS.Second = ICK_Complex_Real;
1582 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001583 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001584 // Floating point conversions (C++ 4.8).
1585 SCS.Second = ICK_Floating_Conversion;
1586 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001587 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001588 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001589 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001590 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001591 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001592 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001593 FromType = ToType.getUnqualifiedType();
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001594 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCallf85e1932011-06-15 23:02:42 +00001595 SCS.Second = ICK_Block_Pointer_Conversion;
1596 } else if (AllowObjCWritebackConversion &&
1597 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1598 SCS.Second = ICK_Writeback_Conversion;
John McCall120d63c2010-08-24 20:38:10 +00001599 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1600 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001601 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001602 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001603 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001604 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001605 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall120d63c2010-08-24 20:38:10 +00001606 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001607 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001608 SCS.Second = ICK_Pointer_Member;
John McCall120d63c2010-08-24 20:38:10 +00001609 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001610 SCS.Second = SecondICK;
1611 FromType = ToType.getUnqualifiedType();
David Blaikie4e4d0842012-03-11 07:00:24 +00001612 } else if (!S.getLangOpts().CPlusPlus &&
John McCall120d63c2010-08-24 20:38:10 +00001613 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001614 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001615 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001616 FromType = ToType.getUnqualifiedType();
Chandler Carruth18e04612011-06-18 01:19:03 +00001617 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001618 // Treat a conversion that strips "noreturn" as an identity conversion.
1619 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001620 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1621 InOverloadResolution,
1622 SCS, CStyle)) {
1623 SCS.Second = ICK_TransparentUnionConversion;
1624 FromType = ToType;
Douglas Gregor7d000652012-04-12 20:48:09 +00001625 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1626 CStyle)) {
1627 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001628 // appropriately.
1629 return true;
Guy Benyei6959acd2013-02-07 16:05:33 +00001630 } else if (ToType->isEventT() &&
1631 From->isIntegerConstantExpr(S.getASTContext()) &&
1632 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1633 SCS.Second = ICK_Zero_Event_Conversion;
1634 FromType = ToType;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001635 } else {
1636 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001637 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001638 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001639 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001640
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001641 QualType CanonFrom;
1642 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001643 // The third conversion can be a qualification conversion (C++ 4p1).
John McCallf85e1932011-06-15 23:02:42 +00001644 bool ObjCLifetimeConversion;
1645 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1646 ObjCLifetimeConversion)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001647 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001648 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001649 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001650 CanonFrom = S.Context.getCanonicalType(FromType);
1651 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001652 } else {
1653 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001654 SCS.Third = ICK_Identity;
1655
Mike Stump1eb44332009-09-09 15:08:12 +00001656 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001657 // [...] Any difference in top-level cv-qualification is
1658 // subsumed by the initialization itself and does not constitute
1659 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001660 CanonFrom = S.Context.getCanonicalType(FromType);
1661 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001662 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregora4923eb2009-11-16 21:35:15 +00001663 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault5509f372013-02-26 21:15:54 +00001664 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001665 FromType = ToType;
1666 CanonFrom = CanonTo;
1667 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001668 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001669 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001670
1671 // If we have not converted the argument type to the parameter type,
1672 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001673 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001674 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001675
Douglas Gregor60d62c22008-10-31 16:23:19 +00001676 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001677}
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001678
1679static bool
1680IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1681 QualType &ToType,
1682 bool InOverloadResolution,
1683 StandardConversionSequence &SCS,
1684 bool CStyle) {
1685
1686 const RecordType *UT = ToType->getAsUnionType();
1687 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1688 return false;
1689 // The field to initialize within the transparent union.
1690 RecordDecl *UD = UT->getDecl();
1691 // It's compatible if the expression matches any of the fields.
1692 for (RecordDecl::field_iterator it = UD->field_begin(),
1693 itend = UD->field_end();
1694 it != itend; ++it) {
John McCallf85e1932011-06-15 23:02:42 +00001695 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1696 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001697 ToType = it->getType();
1698 return true;
1699 }
1700 }
1701 return false;
1702}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001703
1704/// IsIntegralPromotion - Determines whether the conversion from the
1705/// expression From (whose potentially-adjusted type is FromType) to
1706/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1707/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001708bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001709 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001710 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001711 if (!To) {
1712 return false;
1713 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001714
1715 // An rvalue of type char, signed char, unsigned char, short int, or
1716 // unsigned short int can be converted to an rvalue of type int if
1717 // int can represent all the values of the source type; otherwise,
1718 // the source rvalue can be converted to an rvalue of type unsigned
1719 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001720 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1721 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001722 if (// We can promote any signed, promotable integer type to an int
1723 (FromType->isSignedIntegerType() ||
1724 // We can promote any unsigned integer type whose size is
1725 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001726 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001727 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001728 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001729 }
1730
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001731 return To->getKind() == BuiltinType::UInt;
1732 }
1733
Richard Smithe7ff9192012-09-13 21:18:54 +00001734 // C++11 [conv.prom]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001735 // A prvalue of an unscoped enumeration type whose underlying type is not
1736 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1737 // following types that can represent all the values of the enumeration
1738 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1739 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001740 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001741 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001742 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001743 // with lowest integer conversion rank (4.13) greater than the rank of long
1744 // long in which all the values of the enumeration can be represented. If
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001745 // there are two such extended types, the signed one is chosen.
Richard Smithe7ff9192012-09-13 21:18:54 +00001746 // C++11 [conv.prom]p4:
1747 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1748 // can be converted to a prvalue of its underlying type. Moreover, if
1749 // integral promotion can be applied to its underlying type, a prvalue of an
1750 // unscoped enumeration type whose underlying type is fixed can also be
1751 // converted to a prvalue of the promoted underlying type.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001752 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1753 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1754 // provided for a scoped enumeration.
1755 if (FromEnumType->getDecl()->isScoped())
1756 return false;
1757
Richard Smithe7ff9192012-09-13 21:18:54 +00001758 // We can perform an integral promotion to the underlying type of the enum,
1759 // even if that's not the promoted type.
1760 if (FromEnumType->getDecl()->isFixed()) {
1761 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1762 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1763 IsIntegralPromotion(From, Underlying, ToType);
1764 }
1765
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001766 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001767 if (ToType->isIntegerType() &&
Douglas Gregord10099e2012-05-04 16:32:21 +00001768 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall842aef82009-12-09 09:09:27 +00001769 return Context.hasSameUnqualifiedType(ToType,
1770 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001771 }
John McCall842aef82009-12-09 09:09:27 +00001772
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001773 // C++0x [conv.prom]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001774 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1775 // to an rvalue a prvalue of the first of the following types that can
1776 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001777 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001778 // If none of the types in that list can represent all the values of its
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001779 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001780 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001781 // type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001782 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001783 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001784 // Determine whether the type we're converting from is signed or
1785 // unsigned.
David Majnemer0ad92312011-07-22 21:09:04 +00001786 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001787 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001788
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001789 // The types we'll try to promote to, in the appropriate
1790 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001791 QualType PromoteTypes[6] = {
1792 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001793 Context.LongTy, Context.UnsignedLongTy ,
1794 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001795 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001796 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001797 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1798 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001799 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001800 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1801 // We found the type that we can promote to. If this is the
1802 // type we wanted, we have a promotion. Otherwise, no
1803 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001804 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001805 }
1806 }
1807 }
1808
1809 // An rvalue for an integral bit-field (9.6) can be converted to an
1810 // rvalue of type int if int can represent all the values of the
1811 // bit-field; otherwise, it can be converted to unsigned int if
1812 // unsigned int can represent all the values of the bit-field. If
1813 // the bit-field is larger yet, no integral promotion applies to
1814 // it. If the bit-field has an enumerated type, it is treated as any
1815 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001816 // FIXME: We should delay checking of bit-fields until we actually perform the
1817 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001818 using llvm::APSInt;
1819 if (From)
John McCall993f43f2013-05-06 21:39:12 +00001820 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001821 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001822 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001823 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1824 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1825 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001826
Douglas Gregor86f19402008-12-20 23:49:58 +00001827 // Are we promoting to an int from a bitfield that fits in an int?
1828 if (BitWidth < ToSize ||
1829 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1830 return To->getKind() == BuiltinType::Int;
1831 }
Mike Stump1eb44332009-09-09 15:08:12 +00001832
Douglas Gregor86f19402008-12-20 23:49:58 +00001833 // Are we promoting to an unsigned int from an unsigned bitfield
1834 // that fits into an unsigned int?
1835 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1836 return To->getKind() == BuiltinType::UInt;
1837 }
Mike Stump1eb44332009-09-09 15:08:12 +00001838
Douglas Gregor86f19402008-12-20 23:49:58 +00001839 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001840 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001841 }
Mike Stump1eb44332009-09-09 15:08:12 +00001842
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001843 // An rvalue of type bool can be converted to an rvalue of type int,
1844 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001845 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001846 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001847 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001848
1849 return false;
1850}
1851
1852/// IsFloatingPointPromotion - Determines whether the conversion from
1853/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1854/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001855bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001856 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1857 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001858 /// An rvalue of type float can be converted to an rvalue of type
1859 /// double. (C++ 4.6p1).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001860 if (FromBuiltin->getKind() == BuiltinType::Float &&
1861 ToBuiltin->getKind() == BuiltinType::Double)
1862 return true;
1863
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001864 // C99 6.3.1.5p1:
1865 // When a float is promoted to double or long double, or a
1866 // double is promoted to long double [...].
David Blaikie4e4d0842012-03-11 07:00:24 +00001867 if (!getLangOpts().CPlusPlus &&
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001868 (FromBuiltin->getKind() == BuiltinType::Float ||
1869 FromBuiltin->getKind() == BuiltinType::Double) &&
1870 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1871 return true;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001872
1873 // Half can be promoted to float.
Joey Gouly19dbb202013-01-23 11:56:20 +00001874 if (!getLangOpts().NativeHalfType &&
1875 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001876 ToBuiltin->getKind() == BuiltinType::Float)
1877 return true;
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001878 }
1879
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001880 return false;
1881}
1882
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001883/// \brief Determine if a conversion is a complex promotion.
1884///
1885/// A complex promotion is defined as a complex -> complex conversion
1886/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001887/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001888bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001889 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001890 if (!FromComplex)
1891 return false;
1892
John McCall183700f2009-09-21 23:43:11 +00001893 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001894 if (!ToComplex)
1895 return false;
1896
1897 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001898 ToComplex->getElementType()) ||
1899 IsIntegralPromotion(0, FromComplex->getElementType(),
1900 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001901}
1902
Douglas Gregorcb7de522008-11-26 23:31:11 +00001903/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1904/// the pointer type FromPtr to a pointer to type ToPointee, with the
1905/// same type qualifiers as FromPtr has on its pointee type. ToType,
1906/// if non-empty, will be a pointer to ToType that may or may not have
1907/// the right set of qualifiers on its pointee.
John McCallf85e1932011-06-15 23:02:42 +00001908///
Mike Stump1eb44332009-09-09 15:08:12 +00001909static QualType
Douglas Gregorda80f742010-12-01 21:43:58 +00001910BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001911 QualType ToPointee, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00001912 ASTContext &Context,
1913 bool StripObjCLifetime = false) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001914 assert((FromPtr->getTypeClass() == Type::Pointer ||
1915 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1916 "Invalid similarly-qualified pointer type");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001917
John McCallf85e1932011-06-15 23:02:42 +00001918 /// Conversions to 'id' subsume cv-qualifier conversions.
1919 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregor143c7ac2010-12-06 22:09:19 +00001920 return ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001921
1922 QualType CanonFromPointee
Douglas Gregorda80f742010-12-01 21:43:58 +00001923 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregorcb7de522008-11-26 23:31:11 +00001924 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001925 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001926
John McCallf85e1932011-06-15 23:02:42 +00001927 if (StripObjCLifetime)
1928 Quals.removeObjCLifetime();
1929
Mike Stump1eb44332009-09-09 15:08:12 +00001930 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001931 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001932 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001933 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001934 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001935
1936 // Build a pointer to ToPointee. It has the right qualifiers
1937 // already.
Douglas Gregorda80f742010-12-01 21:43:58 +00001938 if (isa<ObjCObjectPointerType>(ToType))
1939 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregorcb7de522008-11-26 23:31:11 +00001940 return Context.getPointerType(ToPointee);
1941 }
1942
1943 // Just build a canonical type that has the right qualifiers.
Douglas Gregorda80f742010-12-01 21:43:58 +00001944 QualType QualifiedCanonToPointee
1945 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001946
Douglas Gregorda80f742010-12-01 21:43:58 +00001947 if (isa<ObjCObjectPointerType>(ToType))
1948 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1949 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001950}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001951
Mike Stump1eb44332009-09-09 15:08:12 +00001952static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001953 bool InOverloadResolution,
1954 ASTContext &Context) {
1955 // Handle value-dependent integral null pointer constants correctly.
1956 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1957 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001958 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001959 return !InOverloadResolution;
1960
Douglas Gregorce940492009-09-25 04:25:58 +00001961 return Expr->isNullPointerConstant(Context,
1962 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1963 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001964}
Mike Stump1eb44332009-09-09 15:08:12 +00001965
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001966/// IsPointerConversion - Determines whether the conversion of the
1967/// expression From, which has the (possibly adjusted) type FromType,
1968/// can be converted to the type ToType via a pointer conversion (C++
1969/// 4.10). If so, returns true and places the converted type (that
1970/// might differ from ToType in its cv-qualifiers at some level) into
1971/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001972///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001973/// This routine also supports conversions to and from block pointers
1974/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1975/// pointers to interfaces. FIXME: Once we've determined the
1976/// appropriate overloading rules for Objective-C, we may want to
1977/// split the Objective-C checks into a different routine; however,
1978/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001979/// conversions, so for now they live here. IncompatibleObjC will be
1980/// set if the conversion is an allowed Objective-C conversion that
1981/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001982bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001983 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001984 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001985 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001986 IncompatibleObjC = false;
Chandler Carruth6df868e2010-12-12 08:17:55 +00001987 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1988 IncompatibleObjC))
Douglas Gregorc7887512008-12-19 19:13:09 +00001989 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001990
Mike Stump1eb44332009-09-09 15:08:12 +00001991 // Conversion from a null pointer constant to any Objective-C pointer type.
1992 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001993 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001994 ConvertedType = ToType;
1995 return true;
1996 }
1997
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001998 // Blocks: Block pointers can be converted to void*.
1999 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002000 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002001 ConvertedType = ToType;
2002 return true;
2003 }
2004 // Blocks: A null pointer constant can be converted to a block
2005 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00002006 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002007 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002008 ConvertedType = ToType;
2009 return true;
2010 }
2011
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002012 // If the left-hand-side is nullptr_t, the right side can be a null
2013 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00002014 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002015 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002016 ConvertedType = ToType;
2017 return true;
2018 }
2019
Ted Kremenek6217b802009-07-29 21:53:49 +00002020 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002021 if (!ToTypePtr)
2022 return false;
2023
2024 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002025 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002026 ConvertedType = ToType;
2027 return true;
2028 }
Sebastian Redl07779722008-10-31 14:43:28 +00002029
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002030 // Beyond this point, both types need to be pointers
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002031 // , including objective-c pointers.
2032 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002033 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002034 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002035 ConvertedType = BuildSimilarlyQualifiedPointerType(
2036 FromType->getAs<ObjCObjectPointerType>(),
2037 ToPointeeType,
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002038 ToType, Context);
2039 return true;
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002040 }
Ted Kremenek6217b802009-07-29 21:53:49 +00002041 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002042 if (!FromTypePtr)
2043 return false;
2044
2045 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002046
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002047 // If the unqualified pointee types are the same, this can't be a
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00002048 // pointer conversion, so don't do all of the work below.
2049 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2050 return false;
2051
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002052 // An rvalue of type "pointer to cv T," where T is an object type,
2053 // can be converted to an rvalue of type "pointer to cv void" (C++
2054 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00002055 if (FromPointeeType->isIncompleteOrObjectType() &&
2056 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002057 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002058 ToPointeeType,
John McCallf85e1932011-06-15 23:02:42 +00002059 ToType, Context,
2060 /*StripObjCLifetime=*/true);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002061 return true;
2062 }
2063
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002064 // MSVC allows implicit function to void* type conversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002065 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002066 ToPointeeType->isVoidType()) {
2067 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2068 ToPointeeType,
2069 ToType, Context);
2070 return true;
2071 }
2072
Douglas Gregorf9201e02009-02-11 23:02:49 +00002073 // When we're overloading in C, we allow a special kind of pointer
2074 // conversion for compatible-but-not-identical pointee types.
David Blaikie4e4d0842012-03-11 07:00:24 +00002075 if (!getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002076 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002077 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00002078 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00002079 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00002080 return true;
2081 }
2082
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002083 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00002084 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002085 // An rvalue of type "pointer to cv D," where D is a class type,
2086 // can be converted to an rvalue of type "pointer to cv B," where
2087 // B is a base class (clause 10) of D. If B is an inaccessible
2088 // (clause 11) or ambiguous (10.2) base class of D, a program that
2089 // necessitates this conversion is ill-formed. The result of the
2090 // conversion is a pointer to the base class sub-object of the
2091 // derived class object. The null pointer value is converted to
2092 // the null pointer value of the destination type.
2093 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002094 // Note that we do not check for ambiguity or inaccessibility
2095 // here. That is handled by CheckPointerConversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002096 if (getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002097 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00002098 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002099 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00002100 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002101 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002102 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002103 ToType, Context);
2104 return true;
2105 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002106
Fariborz Jahanian5da3c082011-04-14 20:33:36 +00002107 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2108 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2109 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2110 ToPointeeType,
2111 ToType, Context);
2112 return true;
2113 }
2114
Douglas Gregorc7887512008-12-19 19:13:09 +00002115 return false;
2116}
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002117
2118/// \brief Adopt the given qualifiers for the given type.
2119static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2120 Qualifiers TQs = T.getQualifiers();
2121
2122 // Check whether qualifiers already match.
2123 if (TQs == Qs)
2124 return T;
2125
2126 if (Qs.compatiblyIncludes(TQs))
2127 return Context.getQualifiedType(T, Qs);
2128
2129 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2130}
Douglas Gregorc7887512008-12-19 19:13:09 +00002131
2132/// isObjCPointerConversion - Determines whether this is an
2133/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2134/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00002135bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00002136 QualType& ConvertedType,
2137 bool &IncompatibleObjC) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002138 if (!getLangOpts().ObjC1)
Douglas Gregorc7887512008-12-19 19:13:09 +00002139 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002140
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002141 // The set of qualifiers on the type we're converting from.
2142 Qualifiers FromQualifiers = FromType.getQualifiers();
2143
Steve Naroff14108da2009-07-10 23:34:53 +00002144 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth6df868e2010-12-12 08:17:55 +00002145 const ObjCObjectPointerType* ToObjCPtr =
2146 ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002147 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00002148 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002149
Steve Naroff14108da2009-07-10 23:34:53 +00002150 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002151 // If the pointee types are the same (ignoring qualifications),
2152 // then this is not a pointer conversion.
2153 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2154 FromObjCPtr->getPointeeType()))
2155 return false;
2156
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002157 // Check for compatible
Steve Naroffde2e22d2009-07-15 18:40:39 +00002158 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00002159 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00002160 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002161 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002162 return true;
2163 }
2164 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00002165 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00002166 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00002167 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00002168 /*compare=*/false)) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002169 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002170 return true;
2171 }
2172 // Objective C++: We're able to convert from a pointer to an
2173 // interface to a pointer to a different interface.
2174 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002175 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2176 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002177 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002178 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2179 FromObjCPtr->getPointeeType()))
2180 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002181 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002182 ToObjCPtr->getPointeeType(),
2183 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002184 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002185 return true;
2186 }
2187
2188 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2189 // Okay: this is some kind of implicit downcast of Objective-C
2190 // interfaces, which is permitted. However, we're going to
2191 // complain about it.
2192 IncompatibleObjC = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002193 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002194 ToObjCPtr->getPointeeType(),
2195 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002196 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002197 return true;
2198 }
Mike Stump1eb44332009-09-09 15:08:12 +00002199 }
Steve Naroff14108da2009-07-10 23:34:53 +00002200 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002201 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002202 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002203 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002204 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002205 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00002206 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002207 // to a block pointer type.
2208 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002209 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002210 return true;
2211 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002212 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002213 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002214 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002215 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002216 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00002217 // pointer to any object.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002218 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002219 return true;
2220 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002221 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002222 return false;
2223
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002224 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002225 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002226 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth6df868e2010-12-12 08:17:55 +00002227 else if (const BlockPointerType *FromBlockPtr =
2228 FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002229 FromPointeeType = FromBlockPtr->getPointeeType();
2230 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002231 return false;
2232
Douglas Gregorc7887512008-12-19 19:13:09 +00002233 // If we have pointers to pointers, recursively check whether this
2234 // is an Objective-C conversion.
2235 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2236 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2237 IncompatibleObjC)) {
2238 // We always complain about this conversion.
2239 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00002240 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002241 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002242 return true;
2243 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002244 // Allow conversion of pointee being objective-c pointer to another one;
2245 // as in I* to id.
2246 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2247 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2248 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2249 IncompatibleObjC)) {
John McCallf85e1932011-06-15 23:02:42 +00002250
Douglas Gregorda80f742010-12-01 21:43:58 +00002251 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002252 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002253 return true;
2254 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002255
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002256 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00002257 // differences in the argument and result types are in Objective-C
2258 // pointer conversions. If so, we permit the conversion (but
2259 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00002260 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00002261 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00002262 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00002263 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002264 if (FromFunctionType && ToFunctionType) {
2265 // If the function types are exactly the same, this isn't an
2266 // Objective-C pointer conversion.
2267 if (Context.getCanonicalType(FromPointeeType)
2268 == Context.getCanonicalType(ToPointeeType))
2269 return false;
2270
2271 // Perform the quick checks that will tell us whether these
2272 // function types are obviously different.
2273 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2274 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2275 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2276 return false;
2277
2278 bool HasObjCConversion = false;
2279 if (Context.getCanonicalType(FromFunctionType->getResultType())
2280 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2281 // Okay, the types match exactly. Nothing to do.
2282 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2283 ToFunctionType->getResultType(),
2284 ConvertedType, IncompatibleObjC)) {
2285 // Okay, we have an Objective-C pointer conversion.
2286 HasObjCConversion = true;
2287 } else {
2288 // Function types are too different. Abort.
2289 return false;
2290 }
Mike Stump1eb44332009-09-09 15:08:12 +00002291
Douglas Gregorc7887512008-12-19 19:13:09 +00002292 // Check argument types.
2293 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2294 ArgIdx != NumArgs; ++ArgIdx) {
2295 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2296 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2297 if (Context.getCanonicalType(FromArgType)
2298 == Context.getCanonicalType(ToArgType)) {
2299 // Okay, the types match exactly. Nothing to do.
2300 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2301 ConvertedType, IncompatibleObjC)) {
2302 // Okay, we have an Objective-C pointer conversion.
2303 HasObjCConversion = true;
2304 } else {
2305 // Argument types are too different. Abort.
2306 return false;
2307 }
2308 }
2309
2310 if (HasObjCConversion) {
2311 // We had an Objective-C conversion. Allow this pointer
2312 // conversion, but complain about it.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002313 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002314 IncompatibleObjC = true;
2315 return true;
2316 }
2317 }
2318
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002319 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002320}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002321
John McCallf85e1932011-06-15 23:02:42 +00002322/// \brief Determine whether this is an Objective-C writeback conversion,
2323/// used for parameter passing when performing automatic reference counting.
2324///
2325/// \param FromType The type we're converting form.
2326///
2327/// \param ToType The type we're converting to.
2328///
2329/// \param ConvertedType The type that will be produced after applying
2330/// this conversion.
2331bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2332 QualType &ConvertedType) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002333 if (!getLangOpts().ObjCAutoRefCount ||
John McCallf85e1932011-06-15 23:02:42 +00002334 Context.hasSameUnqualifiedType(FromType, ToType))
2335 return false;
2336
2337 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2338 QualType ToPointee;
2339 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2340 ToPointee = ToPointer->getPointeeType();
2341 else
2342 return false;
2343
2344 Qualifiers ToQuals = ToPointee.getQualifiers();
2345 if (!ToPointee->isObjCLifetimeType() ||
2346 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall200fa532012-02-08 00:46:36 +00002347 !ToQuals.withoutObjCLifetime().empty())
John McCallf85e1932011-06-15 23:02:42 +00002348 return false;
2349
2350 // Argument must be a pointer to __strong to __weak.
2351 QualType FromPointee;
2352 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2353 FromPointee = FromPointer->getPointeeType();
2354 else
2355 return false;
2356
2357 Qualifiers FromQuals = FromPointee.getQualifiers();
2358 if (!FromPointee->isObjCLifetimeType() ||
2359 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2360 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2361 return false;
2362
2363 // Make sure that we have compatible qualifiers.
2364 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2365 if (!ToQuals.compatiblyIncludes(FromQuals))
2366 return false;
2367
2368 // Remove qualifiers from the pointee type we're converting from; they
2369 // aren't used in the compatibility check belong, and we'll be adding back
2370 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2371 FromPointee = FromPointee.getUnqualifiedType();
2372
2373 // The unqualified form of the pointee types must be compatible.
2374 ToPointee = ToPointee.getUnqualifiedType();
2375 bool IncompatibleObjC;
2376 if (Context.typesAreCompatible(FromPointee, ToPointee))
2377 FromPointee = ToPointee;
2378 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2379 IncompatibleObjC))
2380 return false;
2381
2382 /// \brief Construct the type we're converting to, which is a pointer to
2383 /// __autoreleasing pointee.
2384 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2385 ConvertedType = Context.getPointerType(FromPointee);
2386 return true;
2387}
2388
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002389bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2390 QualType& ConvertedType) {
2391 QualType ToPointeeType;
2392 if (const BlockPointerType *ToBlockPtr =
2393 ToType->getAs<BlockPointerType>())
2394 ToPointeeType = ToBlockPtr->getPointeeType();
2395 else
2396 return false;
2397
2398 QualType FromPointeeType;
2399 if (const BlockPointerType *FromBlockPtr =
2400 FromType->getAs<BlockPointerType>())
2401 FromPointeeType = FromBlockPtr->getPointeeType();
2402 else
2403 return false;
2404 // We have pointer to blocks, check whether the only
2405 // differences in the argument and result types are in Objective-C
2406 // pointer conversions. If so, we permit the conversion.
2407
2408 const FunctionProtoType *FromFunctionType
2409 = FromPointeeType->getAs<FunctionProtoType>();
2410 const FunctionProtoType *ToFunctionType
2411 = ToPointeeType->getAs<FunctionProtoType>();
2412
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002413 if (!FromFunctionType || !ToFunctionType)
2414 return false;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002415
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002416 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002417 return true;
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002418
2419 // Perform the quick checks that will tell us whether these
2420 // function types are obviously different.
2421 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2422 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2423 return false;
2424
2425 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2426 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2427 if (FromEInfo != ToEInfo)
2428 return false;
2429
2430 bool IncompatibleObjC = false;
Fariborz Jahanian462dae52011-02-13 20:11:42 +00002431 if (Context.hasSameType(FromFunctionType->getResultType(),
2432 ToFunctionType->getResultType())) {
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002433 // Okay, the types match exactly. Nothing to do.
2434 } else {
2435 QualType RHS = FromFunctionType->getResultType();
2436 QualType LHS = ToFunctionType->getResultType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002437 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002438 !RHS.hasQualifiers() && LHS.hasQualifiers())
2439 LHS = LHS.getUnqualifiedType();
2440
2441 if (Context.hasSameType(RHS,LHS)) {
2442 // OK exact match.
2443 } else if (isObjCPointerConversion(RHS, LHS,
2444 ConvertedType, IncompatibleObjC)) {
2445 if (IncompatibleObjC)
2446 return false;
2447 // Okay, we have an Objective-C pointer conversion.
2448 }
2449 else
2450 return false;
2451 }
2452
2453 // Check argument types.
2454 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2455 ArgIdx != NumArgs; ++ArgIdx) {
2456 IncompatibleObjC = false;
2457 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2458 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2459 if (Context.hasSameType(FromArgType, ToArgType)) {
2460 // Okay, the types match exactly. Nothing to do.
2461 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2462 ConvertedType, IncompatibleObjC)) {
2463 if (IncompatibleObjC)
2464 return false;
2465 // Okay, we have an Objective-C pointer conversion.
2466 } else
2467 // Argument types are too different. Abort.
2468 return false;
2469 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00002470 if (LangOpts.ObjCAutoRefCount &&
2471 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2472 ToFunctionType))
2473 return false;
Fariborz Jahanianf9d95272011-09-28 20:22:05 +00002474
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002475 ConvertedType = ToType;
2476 return true;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002477}
2478
Richard Trieu6efd4c52011-11-23 22:32:32 +00002479enum {
2480 ft_default,
2481 ft_different_class,
2482 ft_parameter_arity,
2483 ft_parameter_mismatch,
2484 ft_return_type,
2485 ft_qualifer_mismatch
2486};
2487
2488/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2489/// function types. Catches different number of parameter, mismatch in
2490/// parameter types, and different return types.
2491void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2492 QualType FromType, QualType ToType) {
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002493 // If either type is not valid, include no extra info.
2494 if (FromType.isNull() || ToType.isNull()) {
2495 PDiag << ft_default;
2496 return;
2497 }
2498
Richard Trieu6efd4c52011-11-23 22:32:32 +00002499 // Get the function type from the pointers.
2500 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2501 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2502 *ToMember = ToType->getAs<MemberPointerType>();
2503 if (FromMember->getClass() != ToMember->getClass()) {
2504 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2505 << QualType(FromMember->getClass(), 0);
2506 return;
2507 }
2508 FromType = FromMember->getPointeeType();
2509 ToType = ToMember->getPointeeType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00002510 }
2511
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002512 if (FromType->isPointerType())
2513 FromType = FromType->getPointeeType();
2514 if (ToType->isPointerType())
2515 ToType = ToType->getPointeeType();
2516
2517 // Remove references.
Richard Trieu6efd4c52011-11-23 22:32:32 +00002518 FromType = FromType.getNonReferenceType();
2519 ToType = ToType.getNonReferenceType();
2520
Richard Trieu6efd4c52011-11-23 22:32:32 +00002521 // Don't print extra info for non-specialized template functions.
2522 if (FromType->isInstantiationDependentType() &&
2523 !FromType->getAs<TemplateSpecializationType>()) {
2524 PDiag << ft_default;
2525 return;
2526 }
2527
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002528 // No extra info for same types.
2529 if (Context.hasSameType(FromType, ToType)) {
2530 PDiag << ft_default;
2531 return;
2532 }
2533
Richard Trieu6efd4c52011-11-23 22:32:32 +00002534 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2535 *ToFunction = ToType->getAs<FunctionProtoType>();
2536
2537 // Both types need to be function types.
2538 if (!FromFunction || !ToFunction) {
2539 PDiag << ft_default;
2540 return;
2541 }
2542
2543 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2544 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2545 << FromFunction->getNumArgs();
2546 return;
2547 }
2548
2549 // Handle different parameter types.
2550 unsigned ArgPos;
2551 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2552 PDiag << ft_parameter_mismatch << ArgPos + 1
2553 << ToFunction->getArgType(ArgPos)
2554 << FromFunction->getArgType(ArgPos);
2555 return;
2556 }
2557
2558 // Handle different return type.
2559 if (!Context.hasSameType(FromFunction->getResultType(),
2560 ToFunction->getResultType())) {
2561 PDiag << ft_return_type << ToFunction->getResultType()
2562 << FromFunction->getResultType();
2563 return;
2564 }
2565
2566 unsigned FromQuals = FromFunction->getTypeQuals(),
2567 ToQuals = ToFunction->getTypeQuals();
2568 if (FromQuals != ToQuals) {
2569 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2570 return;
2571 }
2572
2573 // Unable to find a difference, so add no extra info.
2574 PDiag << ft_default;
2575}
2576
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002577/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregordec1cc42011-12-15 17:15:07 +00002578/// for equality of their argument types. Caller has already checked that
Eli Friedman06017002013-06-18 22:41:37 +00002579/// they have same number of arguments. If the parameters are different,
2580/// ArgPos will have the parameter index of the first different parameter.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002581bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieu6efd4c52011-11-23 22:32:32 +00002582 const FunctionProtoType *NewType,
2583 unsigned *ArgPos) {
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002584 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2585 N = NewType->arg_type_begin(),
2586 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
Richard Trieu1a81e742013-08-06 03:44:10 +00002587 if (!(*O)->isReferenceType() && !(*N)->isReferenceType()) {
2588 if (!Context.hasSameType(O->getUnqualifiedType(),
2589 N->getUnqualifiedType())) {
2590 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2591 return false;
2592 }
2593 } else {
2594 if (!Context.hasSameType(*O, *N)) {
2595 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2596 return false;
2597 }
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002598 }
2599 }
2600 return true;
2601}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002602
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002603/// CheckPointerConversion - Check the pointer conversion from the
2604/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002605/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002606/// conversions for which IsPointerConversion has already returned
2607/// true. It returns true and produces a diagnostic if there was an
2608/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00002609bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002610 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002611 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002612 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002613 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00002614 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002615
John McCalldaa8e4e2010-11-15 09:13:47 +00002616 Kind = CK_BitCast;
2617
David Blaikie50800fc2012-08-08 17:33:31 +00002618 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2619 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2620 Expr::NPCK_ZeroExpression) {
2621 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2622 DiagRuntimeBehavior(From->getExprLoc(), From,
2623 PDiag(diag::warn_impcast_bool_to_null_pointer)
2624 << ToType << From->getSourceRange());
2625 else if (!isUnevaluatedContext())
2626 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2627 << ToType << From->getSourceRange();
2628 }
John McCall1d9b3b22011-09-09 05:25:32 +00002629 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2630 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002631 QualType FromPointeeType = FromPtrType->getPointeeType(),
2632 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00002633
Douglas Gregor5fccd362010-03-03 23:55:11 +00002634 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2635 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002636 // We must have a derived-to-base conversion. Check an
2637 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00002638 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2639 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002640 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002641 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00002642 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002643
Anders Carlsson61faec12009-09-12 04:46:44 +00002644 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00002645 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002646 }
2647 }
John McCall1d9b3b22011-09-09 05:25:32 +00002648 } else if (const ObjCObjectPointerType *ToPtrType =
2649 ToType->getAs<ObjCObjectPointerType>()) {
2650 if (const ObjCObjectPointerType *FromPtrType =
2651 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002652 // Objective-C++ conversions are always okay.
2653 // FIXME: We should have a different class of conversions for the
2654 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00002655 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00002656 return false;
John McCall1d9b3b22011-09-09 05:25:32 +00002657 } else if (FromType->isBlockPointerType()) {
2658 Kind = CK_BlockPointerToObjCPointerCast;
2659 } else {
2660 Kind = CK_CPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00002661 }
John McCall1d9b3b22011-09-09 05:25:32 +00002662 } else if (ToType->isBlockPointerType()) {
2663 if (!FromType->isBlockPointerType())
2664 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00002665 }
John McCalldaa8e4e2010-11-15 09:13:47 +00002666
2667 // We shouldn't fall into this case unless it's valid for other
2668 // reasons.
2669 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2670 Kind = CK_NullToPointer;
2671
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002672 return false;
2673}
2674
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002675/// IsMemberPointerConversion - Determines whether the conversion of the
2676/// expression From, which has the (possibly adjusted) type FromType, can be
2677/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2678/// If so, returns true and places the converted type (that might differ from
2679/// ToType in its cv-qualifiers at some level) into ConvertedType.
2680bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002681 QualType ToType,
Douglas Gregorce940492009-09-25 04:25:58 +00002682 bool InOverloadResolution,
2683 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002684 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002685 if (!ToTypePtr)
2686 return false;
2687
2688 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00002689 if (From->isNullPointerConstant(Context,
2690 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2691 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002692 ConvertedType = ToType;
2693 return true;
2694 }
2695
2696 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00002697 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002698 if (!FromTypePtr)
2699 return false;
2700
2701 // A pointer to member of B can be converted to a pointer to member of D,
2702 // where D is derived from B (C++ 4.11p2).
2703 QualType FromClass(FromTypePtr->getClass(), 0);
2704 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002705
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002706 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002707 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002708 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002709 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2710 ToClass.getTypePtr());
2711 return true;
2712 }
2713
2714 return false;
2715}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002716
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002717/// CheckMemberPointerConversion - Check the member pointer conversion from the
2718/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00002719/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002720/// for which IsMemberPointerConversion has already returned true. It returns
2721/// true and produces a diagnostic if there was an error, or returns false
2722/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002723bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002724 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002725 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002726 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002727 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002728 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002729 if (!FromPtrType) {
2730 // This must be a null pointer to member pointer conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002731 assert(From->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00002732 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002733 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00002734 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002735 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002736 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002737
Ted Kremenek6217b802009-07-29 21:53:49 +00002738 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00002739 assert(ToPtrType && "No member pointer cast has a target type "
2740 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002741
Sebastian Redl21593ac2009-01-28 18:33:18 +00002742 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2743 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002744
Sebastian Redl21593ac2009-01-28 18:33:18 +00002745 // FIXME: What about dependent types?
2746 assert(FromClass->isRecordType() && "Pointer into non-class.");
2747 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002748
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002749 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002750 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00002751 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2752 assert(DerivationOkay &&
2753 "Should not have been called if derivation isn't OK.");
2754 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002755
Sebastian Redl21593ac2009-01-28 18:33:18 +00002756 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2757 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002758 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2759 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2760 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2761 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002762 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00002763
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002764 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002765 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2766 << FromClass << ToClass << QualType(VBase, 0)
2767 << From->getSourceRange();
2768 return true;
2769 }
2770
John McCall6b2accb2010-02-10 09:31:12 +00002771 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00002772 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2773 Paths.front(),
2774 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00002775
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002776 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002777 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00002778 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002779 return false;
2780}
2781
Douglas Gregor98cd5992008-10-21 23:43:52 +00002782/// IsQualificationConversion - Determines whether the conversion from
2783/// an rvalue of type FromType to ToType is a qualification conversion
2784/// (C++ 4.4).
John McCallf85e1932011-06-15 23:02:42 +00002785///
2786/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2787/// when the qualification conversion involves a change in the Objective-C
2788/// object lifetime.
Mike Stump1eb44332009-09-09 15:08:12 +00002789bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002790Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00002791 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002792 FromType = Context.getCanonicalType(FromType);
2793 ToType = Context.getCanonicalType(ToType);
John McCallf85e1932011-06-15 23:02:42 +00002794 ObjCLifetimeConversion = false;
2795
Douglas Gregor98cd5992008-10-21 23:43:52 +00002796 // If FromType and ToType are the same type, this is not a
2797 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00002798 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00002799 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002800
Douglas Gregor98cd5992008-10-21 23:43:52 +00002801 // (C++ 4.4p4):
2802 // A conversion can add cv-qualifiers at levels other than the first
2803 // in multi-level pointers, subject to the following rules: [...]
2804 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002805 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002806 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002807 // Within each iteration of the loop, we check the qualifiers to
2808 // determine if this still looks like a qualification
2809 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002810 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00002811 // until there are no more pointers or pointers-to-members left to
2812 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00002813 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002814
Douglas Gregor621c92a2011-04-25 18:40:17 +00002815 Qualifiers FromQuals = FromType.getQualifiers();
2816 Qualifiers ToQuals = ToType.getQualifiers();
2817
John McCallf85e1932011-06-15 23:02:42 +00002818 // Objective-C ARC:
2819 // Check Objective-C lifetime conversions.
2820 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2821 UnwrappedAnyPointer) {
2822 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2823 ObjCLifetimeConversion = true;
2824 FromQuals.removeObjCLifetime();
2825 ToQuals.removeObjCLifetime();
2826 } else {
2827 // Qualification conversions cannot cast between different
2828 // Objective-C lifetime qualifiers.
2829 return false;
2830 }
2831 }
2832
Douglas Gregor377e1bd2011-05-08 06:09:53 +00002833 // Allow addition/removal of GC attributes but not changing GC attributes.
2834 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2835 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2836 FromQuals.removeObjCGCAttr();
2837 ToQuals.removeObjCGCAttr();
2838 }
2839
Douglas Gregor98cd5992008-10-21 23:43:52 +00002840 // -- for every j > 0, if const is in cv 1,j then const is in cv
2841 // 2,j, and similarly for volatile.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002842 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002843 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002844
Douglas Gregor98cd5992008-10-21 23:43:52 +00002845 // -- if the cv 1,j and cv 2,j are different, then const is in
2846 // every cv for 0 < k < j.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002847 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00002848 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00002849 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002850
Douglas Gregor98cd5992008-10-21 23:43:52 +00002851 // Keep track of whether all prior cv-qualifiers in the "to" type
2852 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00002853 PreviousToQualsIncludeConst
Douglas Gregor621c92a2011-04-25 18:40:17 +00002854 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregor57373262008-10-22 14:17:15 +00002855 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00002856
2857 // We are left with FromType and ToType being the pointee types
2858 // after unwrapping the original FromType and ToType the same number
2859 // of types. If we unwrapped any pointers, and if FromType and
2860 // ToType have the same unqualified type (since we checked
2861 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002862 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00002863}
2864
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002865/// \brief - Determine whether this is a conversion from a scalar type to an
2866/// atomic type.
2867///
2868/// If successful, updates \c SCS's second and third steps in the conversion
2869/// sequence to finish the conversion.
Douglas Gregor7d000652012-04-12 20:48:09 +00002870static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2871 bool InOverloadResolution,
2872 StandardConversionSequence &SCS,
2873 bool CStyle) {
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002874 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2875 if (!ToAtomic)
2876 return false;
2877
2878 StandardConversionSequence InnerSCS;
2879 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2880 InOverloadResolution, InnerSCS,
2881 CStyle, /*AllowObjCWritebackConversion=*/false))
2882 return false;
2883
2884 SCS.Second = InnerSCS.Second;
2885 SCS.setToType(1, InnerSCS.getToType(1));
2886 SCS.Third = InnerSCS.Third;
2887 SCS.QualificationIncludesObjCLifetime
2888 = InnerSCS.QualificationIncludesObjCLifetime;
2889 SCS.setToType(2, InnerSCS.getToType(2));
2890 return true;
2891}
2892
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002893static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2894 CXXConstructorDecl *Constructor,
2895 QualType Type) {
2896 const FunctionProtoType *CtorType =
2897 Constructor->getType()->getAs<FunctionProtoType>();
2898 if (CtorType->getNumArgs() > 0) {
2899 QualType FirstArg = CtorType->getArgType(0);
2900 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2901 return true;
2902 }
2903 return false;
2904}
2905
Sebastian Redl56a04282012-02-11 23:51:08 +00002906static OverloadingResult
2907IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2908 CXXRecordDecl *To,
2909 UserDefinedConversionSequence &User,
2910 OverloadCandidateSet &CandidateSet,
2911 bool AllowExplicit) {
David Blaikie3bc93e32012-12-19 00:45:41 +00002912 DeclContext::lookup_result R = S.LookupConstructors(To);
2913 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl56a04282012-02-11 23:51:08 +00002914 Con != ConEnd; ++Con) {
2915 NamedDecl *D = *Con;
2916 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2917
2918 // Find the constructor (which may be a template).
2919 CXXConstructorDecl *Constructor = 0;
2920 FunctionTemplateDecl *ConstructorTmpl
2921 = dyn_cast<FunctionTemplateDecl>(D);
2922 if (ConstructorTmpl)
2923 Constructor
2924 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2925 else
2926 Constructor = cast<CXXConstructorDecl>(D);
2927
2928 bool Usable = !Constructor->isInvalidDecl() &&
2929 S.isInitListConstructor(Constructor) &&
2930 (AllowExplicit || !Constructor->isExplicit());
2931 if (Usable) {
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002932 // If the first argument is (a reference to) the target type,
2933 // suppress conversions.
2934 bool SuppressUserConversions =
2935 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl56a04282012-02-11 23:51:08 +00002936 if (ConstructorTmpl)
2937 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2938 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002939 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002940 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002941 else
2942 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002943 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002944 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002945 }
2946 }
2947
2948 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2949
2950 OverloadCandidateSet::iterator Best;
2951 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2952 case OR_Success: {
2953 // Record the standard conversion we used and the conversion function.
2954 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl56a04282012-02-11 23:51:08 +00002955 QualType ThisType = Constructor->getThisType(S.Context);
2956 // Initializer lists don't have conversions as such.
2957 User.Before.setAsIdentityConversion();
2958 User.HadMultipleCandidates = HadMultipleCandidates;
2959 User.ConversionFunction = Constructor;
2960 User.FoundConversionFunction = Best->FoundDecl;
2961 User.After.setAsIdentityConversion();
2962 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2963 User.After.setAllToTypes(ToType);
2964 return OR_Success;
2965 }
2966
2967 case OR_No_Viable_Function:
2968 return OR_No_Viable_Function;
2969 case OR_Deleted:
2970 return OR_Deleted;
2971 case OR_Ambiguous:
2972 return OR_Ambiguous;
2973 }
2974
2975 llvm_unreachable("Invalid OverloadResult!");
2976}
2977
Douglas Gregor734d9862009-01-30 23:27:23 +00002978/// Determines whether there is a user-defined conversion sequence
2979/// (C++ [over.ics.user]) that converts expression From to the type
2980/// ToType. If such a conversion exists, User will contain the
2981/// user-defined conversion sequence that performs such a conversion
2982/// and this routine will return true. Otherwise, this routine returns
2983/// false and User is unspecified.
2984///
Douglas Gregor734d9862009-01-30 23:27:23 +00002985/// \param AllowExplicit true if the conversion should consider C++0x
2986/// "explicit" conversion functions as well as non-explicit conversion
2987/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00002988static OverloadingResult
2989IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl56a04282012-02-11 23:51:08 +00002990 UserDefinedConversionSequence &User,
2991 OverloadCandidateSet &CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00002992 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002993 // Whether we will only visit constructors.
2994 bool ConstructorsOnly = false;
2995
2996 // If the type we are conversion to is a class type, enumerate its
2997 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00002998 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002999 // C++ [over.match.ctor]p1:
3000 // When objects of class type are direct-initialized (8.5), or
3001 // copy-initialized from an expression of the same or a
3002 // derived class type (8.5), overload resolution selects the
3003 // constructor. [...] For copy-initialization, the candidate
3004 // functions are all the converting constructors (12.3.1) of
3005 // that class. The argument list is the expression-list within
3006 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00003007 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003008 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00003009 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003010 ConstructorsOnly = true;
3011
Benjamin Kramer63b6ebe2012-11-23 17:04:52 +00003012 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidise36bca62011-04-22 17:45:37 +00003013 // RequireCompleteType may have returned true due to some invalid decl
3014 // during template instantiation, but ToType may be complete enough now
3015 // to try to recover.
3016 if (ToType->isIncompleteType()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00003017 // We're not going to find any constructors.
3018 } else if (CXXRecordDecl *ToRecordDecl
3019 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003020
3021 Expr **Args = &From;
3022 unsigned NumArgs = 1;
3023 bool ListInitializing = false;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003024 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl56a04282012-02-11 23:51:08 +00003025 // But first, see if there is an init-list-contructor that will work.
3026 OverloadingResult Result = IsInitializerListConstructorConversion(
3027 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3028 if (Result != OR_No_Viable_Function)
3029 return Result;
3030 // Never mind.
3031 CandidateSet.clear();
3032
3033 // If we're list-initializing, we pass the individual elements as
3034 // arguments, not the entire list.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003035 Args = InitList->getInits();
3036 NumArgs = InitList->getNumInits();
3037 ListInitializing = true;
3038 }
3039
David Blaikie3bc93e32012-12-19 00:45:41 +00003040 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3041 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003042 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00003043 NamedDecl *D = *Con;
3044 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3045
Douglas Gregordec06662009-08-21 18:42:58 +00003046 // Find the constructor (which may be a template).
3047 CXXConstructorDecl *Constructor = 0;
3048 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00003049 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00003050 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00003051 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00003052 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3053 else
John McCall9aa472c2010-03-19 07:35:19 +00003054 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003055
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003056 bool Usable = !Constructor->isInvalidDecl();
3057 if (ListInitializing)
3058 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3059 else
3060 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3061 if (Usable) {
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003062 bool SuppressUserConversions = !ConstructorsOnly;
3063 if (SuppressUserConversions && ListInitializing) {
3064 SuppressUserConversions = false;
3065 if (NumArgs == 1) {
3066 // If the first argument is (a reference to) the target type,
3067 // suppress conversions.
Sebastian Redlf78c0f92012-03-27 18:33:03 +00003068 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3069 S.Context, Constructor, ToType);
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003070 }
3071 }
Douglas Gregordec06662009-08-21 18:42:58 +00003072 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00003073 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3074 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003075 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003076 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003077 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00003078 // Allow one user-defined conversion when user specifies a
3079 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00003080 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003081 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003082 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003083 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003084 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003085 }
3086 }
3087
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003088 // Enumerate conversion functions, if we're allowed to.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003089 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003090 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003091 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00003092 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003093 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003094 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003095 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3096 // Add all of the conversion functions as candidates.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003097 std::pair<CXXRecordDecl::conversion_iterator,
3098 CXXRecordDecl::conversion_iterator>
3099 Conversions = FromRecordDecl->getVisibleConversionFunctions();
3100 for (CXXRecordDecl::conversion_iterator
3101 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00003102 DeclAccessPair FoundDecl = I.getPair();
3103 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003104 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3105 if (isa<UsingShadowDecl>(D))
3106 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3107
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003108 CXXConversionDecl *Conv;
3109 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00003110 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3111 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003112 else
John McCall32daa422010-03-31 01:36:47 +00003113 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003114
3115 if (AllowExplicit || !Conv->isExplicit()) {
3116 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00003117 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3118 ActingContext, From, ToType,
3119 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003120 else
John McCall120d63c2010-08-24 20:38:10 +00003121 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3122 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003123 }
3124 }
3125 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003126 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003127
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003128 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3129
Douglas Gregor60d62c22008-10-31 16:23:19 +00003130 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003131 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00003132 case OR_Success:
3133 // Record the standard conversion we used and the conversion function.
3134 if (CXXConstructorDecl *Constructor
3135 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3136 // C++ [over.ics.user]p1:
3137 // If the user-defined conversion is specified by a
3138 // constructor (12.3.1), the initial standard conversion
3139 // sequence converts the source type to the type required by
3140 // the argument of the constructor.
3141 //
3142 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003143 if (isa<InitListExpr>(From)) {
3144 // Initializer lists don't have conversions as such.
3145 User.Before.setAsIdentityConversion();
3146 } else {
3147 if (Best->Conversions[0].isEllipsis())
3148 User.EllipsisConversion = true;
3149 else {
3150 User.Before = Best->Conversions[0].Standard;
3151 User.EllipsisConversion = false;
3152 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003153 }
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003154 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003155 User.ConversionFunction = Constructor;
John McCallca82a822011-09-21 08:36:56 +00003156 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003157 User.After.setAsIdentityConversion();
3158 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3159 User.After.setAllToTypes(ToType);
3160 return OR_Success;
David Blaikie7530c032012-01-17 06:56:22 +00003161 }
3162 if (CXXConversionDecl *Conversion
John McCall120d63c2010-08-24 20:38:10 +00003163 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3164 // C++ [over.ics.user]p1:
3165 //
3166 // [...] If the user-defined conversion is specified by a
3167 // conversion function (12.3.2), the initial standard
3168 // conversion sequence converts the source type to the
3169 // implicit object parameter of the conversion function.
3170 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003171 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003172 User.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00003173 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003174 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003175
John McCall120d63c2010-08-24 20:38:10 +00003176 // C++ [over.ics.user]p2:
3177 // The second standard conversion sequence converts the
3178 // result of the user-defined conversion to the target type
3179 // for the sequence. Since an implicit conversion sequence
3180 // is an initialization, the special rules for
3181 // initialization by user-defined conversion apply when
3182 // selecting the best user-defined conversion for a
3183 // user-defined conversion sequence (see 13.3.3 and
3184 // 13.3.3.1).
3185 User.After = Best->FinalConversion;
3186 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00003187 }
David Blaikie7530c032012-01-17 06:56:22 +00003188 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003189
John McCall120d63c2010-08-24 20:38:10 +00003190 case OR_No_Viable_Function:
3191 return OR_No_Viable_Function;
3192 case OR_Deleted:
3193 // No conversion here! We're done.
3194 return OR_Deleted;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003195
John McCall120d63c2010-08-24 20:38:10 +00003196 case OR_Ambiguous:
3197 return OR_Ambiguous;
3198 }
3199
David Blaikie7530c032012-01-17 06:56:22 +00003200 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003201}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003202
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003203bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003204Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003205 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00003206 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003207 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00003208 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003209 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003210 if (OvResult == OR_Ambiguous)
Daniel Dunbar96a00142012-03-09 18:35:03 +00003211 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003212 diag::err_typecheck_ambiguous_condition)
3213 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo7419d012013-06-27 01:50:25 +00003214 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo288f76a2013-06-27 03:36:30 +00003215 if (!RequireCompleteType(From->getLocStart(), ToType,
Larisse Voufo7419d012013-06-27 01:50:25 +00003216 diag::err_typecheck_nonviable_condition_incomplete,
3217 From->getType(), From->getSourceRange()))
3218 Diag(From->getLocStart(),
3219 diag::err_typecheck_nonviable_condition)
3220 << From->getType() << From->getSourceRange() << ToType;
3221 }
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003222 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003223 return false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003224 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003225 return true;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003226}
Douglas Gregor60d62c22008-10-31 16:23:19 +00003227
Douglas Gregorb734e242012-02-22 17:32:19 +00003228/// \brief Compare the user-defined conversion functions or constructors
3229/// of two user-defined conversion sequences to determine whether any ordering
3230/// is possible.
3231static ImplicitConversionSequence::CompareKind
3232compareConversionFunctions(Sema &S,
3233 FunctionDecl *Function1,
3234 FunctionDecl *Function2) {
Richard Smith80ad52f2013-01-02 11:42:31 +00003235 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregorb734e242012-02-22 17:32:19 +00003236 return ImplicitConversionSequence::Indistinguishable;
3237
3238 // Objective-C++:
3239 // If both conversion functions are implicitly-declared conversions from
3240 // a lambda closure type to a function pointer and a block pointer,
3241 // respectively, always prefer the conversion to a function pointer,
3242 // because the function pointer is more lightweight and is more likely
3243 // to keep code working.
3244 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3245 if (!Conv1)
3246 return ImplicitConversionSequence::Indistinguishable;
3247
3248 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3249 if (!Conv2)
3250 return ImplicitConversionSequence::Indistinguishable;
3251
3252 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3253 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3254 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3255 if (Block1 != Block2)
3256 return Block1? ImplicitConversionSequence::Worse
3257 : ImplicitConversionSequence::Better;
3258 }
3259
3260 return ImplicitConversionSequence::Indistinguishable;
3261}
3262
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003263/// CompareImplicitConversionSequences - Compare two implicit
3264/// conversion sequences to determine whether one is better than the
3265/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00003266static ImplicitConversionSequence::CompareKind
3267CompareImplicitConversionSequences(Sema &S,
3268 const ImplicitConversionSequence& ICS1,
3269 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003270{
3271 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3272 // conversion sequences (as defined in 13.3.3.1)
3273 // -- a standard conversion sequence (13.3.3.1.1) is a better
3274 // conversion sequence than a user-defined conversion sequence or
3275 // an ellipsis conversion sequence, and
3276 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3277 // conversion sequence than an ellipsis conversion sequence
3278 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00003279 //
John McCall1d318332010-01-12 00:44:57 +00003280 // C++0x [over.best.ics]p10:
3281 // For the purpose of ranking implicit conversion sequences as
3282 // described in 13.3.3.2, the ambiguous conversion sequence is
3283 // treated as a user-defined sequence that is indistinguishable
3284 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003285 if (ICS1.getKindRank() < ICS2.getKindRank())
3286 return ImplicitConversionSequence::Better;
David Blaikie7530c032012-01-17 06:56:22 +00003287 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003288 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003289
Benjamin Kramerb6eee072010-04-18 12:05:54 +00003290 // The following checks require both conversion sequences to be of
3291 // the same kind.
3292 if (ICS1.getKind() != ICS2.getKind())
3293 return ImplicitConversionSequence::Indistinguishable;
3294
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003295 ImplicitConversionSequence::CompareKind Result =
3296 ImplicitConversionSequence::Indistinguishable;
3297
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003298 // Two implicit conversion sequences of the same form are
3299 // indistinguishable conversion sequences unless one of the
3300 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00003301 if (ICS1.isStandard())
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003302 Result = CompareStandardConversionSequences(S,
3303 ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00003304 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003305 // User-defined conversion sequence U1 is a better conversion
3306 // sequence than another user-defined conversion sequence U2 if
3307 // they contain the same user-defined conversion function or
3308 // constructor and if the second standard conversion sequence of
3309 // U1 is better than the second standard conversion sequence of
3310 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00003311 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003312 ICS2.UserDefined.ConversionFunction)
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003313 Result = CompareStandardConversionSequences(S,
3314 ICS1.UserDefined.After,
3315 ICS2.UserDefined.After);
Douglas Gregorb734e242012-02-22 17:32:19 +00003316 else
3317 Result = compareConversionFunctions(S,
3318 ICS1.UserDefined.ConversionFunction,
3319 ICS2.UserDefined.ConversionFunction);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003320 }
3321
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003322 // List-initialization sequence L1 is a better conversion sequence than
3323 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3324 // for some X and L2 does not.
3325 if (Result == ImplicitConversionSequence::Indistinguishable &&
Sebastian Redladfb5352012-02-27 22:38:26 +00003326 !ICS1.isBad() &&
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003327 ICS1.isListInitializationSequence() &&
3328 ICS2.isListInitializationSequence()) {
Sebastian Redladfb5352012-02-27 22:38:26 +00003329 if (ICS1.isStdInitializerListElement() &&
3330 !ICS2.isStdInitializerListElement())
3331 return ImplicitConversionSequence::Better;
3332 if (!ICS1.isStdInitializerListElement() &&
3333 ICS2.isStdInitializerListElement())
3334 return ImplicitConversionSequence::Worse;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003335 }
3336
3337 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003338}
3339
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003340static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3341 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3342 Qualifiers Quals;
3343 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003344 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003345 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003346
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003347 return Context.hasSameUnqualifiedType(T1, T2);
3348}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003349
Douglas Gregorad323a82010-01-27 03:51:04 +00003350// Per 13.3.3.2p3, compare the given standard conversion sequences to
3351// determine if one is a proper subset of the other.
3352static ImplicitConversionSequence::CompareKind
3353compareStandardConversionSubsets(ASTContext &Context,
3354 const StandardConversionSequence& SCS1,
3355 const StandardConversionSequence& SCS2) {
3356 ImplicitConversionSequence::CompareKind Result
3357 = ImplicitConversionSequence::Indistinguishable;
3358
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003359 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregorae65f4b2010-05-23 22:10:15 +00003360 // any non-identity conversion sequence
Douglas Gregor4ae5b722011-06-05 06:15:20 +00003361 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3362 return ImplicitConversionSequence::Better;
3363 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3364 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003365
Douglas Gregorad323a82010-01-27 03:51:04 +00003366 if (SCS1.Second != SCS2.Second) {
3367 if (SCS1.Second == ICK_Identity)
3368 Result = ImplicitConversionSequence::Better;
3369 else if (SCS2.Second == ICK_Identity)
3370 Result = ImplicitConversionSequence::Worse;
3371 else
3372 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003373 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00003374 return ImplicitConversionSequence::Indistinguishable;
3375
3376 if (SCS1.Third == SCS2.Third) {
3377 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3378 : ImplicitConversionSequence::Indistinguishable;
3379 }
3380
3381 if (SCS1.Third == ICK_Identity)
3382 return Result == ImplicitConversionSequence::Worse
3383 ? ImplicitConversionSequence::Indistinguishable
3384 : ImplicitConversionSequence::Better;
3385
3386 if (SCS2.Third == ICK_Identity)
3387 return Result == ImplicitConversionSequence::Better
3388 ? ImplicitConversionSequence::Indistinguishable
3389 : ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003390
Douglas Gregorad323a82010-01-27 03:51:04 +00003391 return ImplicitConversionSequence::Indistinguishable;
3392}
3393
Douglas Gregor440a4832011-01-26 14:52:12 +00003394/// \brief Determine whether one of the given reference bindings is better
3395/// than the other based on what kind of bindings they are.
3396static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3397 const StandardConversionSequence &SCS2) {
3398 // C++0x [over.ics.rank]p3b4:
3399 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3400 // implicit object parameter of a non-static member function declared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003401 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregor440a4832011-01-26 14:52:12 +00003402 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003403 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregor440a4832011-01-26 14:52:12 +00003404 // reference*.
3405 //
3406 // FIXME: Rvalue references. We're going rogue with the above edits,
3407 // because the semantics in the current C++0x working paper (N3225 at the
3408 // time of this writing) break the standard definition of std::forward
3409 // and std::reference_wrapper when dealing with references to functions.
3410 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003411 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3412 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3413 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003414
Douglas Gregor440a4832011-01-26 14:52:12 +00003415 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3416 SCS2.IsLvalueReference) ||
3417 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3418 !SCS2.IsLvalueReference);
3419}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003420
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003421/// CompareStandardConversionSequences - Compare two standard
3422/// conversion sequences to determine whether one is better than the
3423/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00003424static ImplicitConversionSequence::CompareKind
3425CompareStandardConversionSequences(Sema &S,
3426 const StandardConversionSequence& SCS1,
3427 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003428{
3429 // Standard conversion sequence S1 is a better conversion sequence
3430 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3431
3432 // -- S1 is a proper subsequence of S2 (comparing the conversion
3433 // sequences in the canonical form defined by 13.3.3.1.1,
3434 // excluding any Lvalue Transformation; the identity conversion
3435 // sequence is considered to be a subsequence of any
3436 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00003437 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00003438 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00003439 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003440
3441 // -- the rank of S1 is better than the rank of S2 (by the rules
3442 // defined below), or, if not that,
3443 ImplicitConversionRank Rank1 = SCS1.getRank();
3444 ImplicitConversionRank Rank2 = SCS2.getRank();
3445 if (Rank1 < Rank2)
3446 return ImplicitConversionSequence::Better;
3447 else if (Rank2 < Rank1)
3448 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003449
Douglas Gregor57373262008-10-22 14:17:15 +00003450 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3451 // are indistinguishable unless one of the following rules
3452 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00003453
Douglas Gregor57373262008-10-22 14:17:15 +00003454 // A conversion that is not a conversion of a pointer, or
3455 // pointer to member, to bool is better than another conversion
3456 // that is such a conversion.
3457 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3458 return SCS2.isPointerConversionToBool()
3459 ? ImplicitConversionSequence::Better
3460 : ImplicitConversionSequence::Worse;
3461
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003462 // C++ [over.ics.rank]p4b2:
3463 //
3464 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003465 // conversion of B* to A* is better than conversion of B* to
3466 // void*, and conversion of A* to void* is better than conversion
3467 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00003468 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003469 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003470 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003471 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003472 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3473 // Exactly one of the conversion sequences is a conversion to
3474 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003475 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3476 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003477 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3478 // Neither conversion sequence converts to a void pointer; compare
3479 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003480 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00003481 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003482 return DerivedCK;
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003483 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3484 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003485 // Both conversion sequences are conversions to void
3486 // pointers. Compare the source types to determine if there's an
3487 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00003488 QualType FromType1 = SCS1.getFromType();
3489 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003490
3491 // Adjust the types we're converting from via the array-to-pointer
3492 // conversion, if we need to.
3493 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003494 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003495 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003496 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003497
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003498 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3499 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003500
John McCall120d63c2010-08-24 20:38:10 +00003501 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00003502 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003503 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00003504 return ImplicitConversionSequence::Worse;
3505
3506 // Objective-C++: If one interface is more specific than the
3507 // other, it is the better one.
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003508 const ObjCObjectPointerType* FromObjCPtr1
3509 = FromType1->getAs<ObjCObjectPointerType>();
3510 const ObjCObjectPointerType* FromObjCPtr2
3511 = FromType2->getAs<ObjCObjectPointerType>();
3512 if (FromObjCPtr1 && FromObjCPtr2) {
3513 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3514 FromObjCPtr2);
3515 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3516 FromObjCPtr1);
3517 if (AssignLeft != AssignRight) {
3518 return AssignLeft? ImplicitConversionSequence::Better
3519 : ImplicitConversionSequence::Worse;
3520 }
Douglas Gregor01919692009-12-13 21:37:05 +00003521 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003522 }
Douglas Gregor57373262008-10-22 14:17:15 +00003523
3524 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3525 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00003526 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00003527 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003528 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00003529
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003530 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregor440a4832011-01-26 14:52:12 +00003531 // Check for a better reference binding based on the kind of bindings.
3532 if (isBetterReferenceBindingKind(SCS1, SCS2))
3533 return ImplicitConversionSequence::Better;
3534 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3535 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003536
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003537 // C++ [over.ics.rank]p3b4:
3538 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3539 // which the references refer are the same type except for
3540 // top-level cv-qualifiers, and the type to which the reference
3541 // initialized by S2 refers is more cv-qualified than the type
3542 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00003543 QualType T1 = SCS1.getToType(2);
3544 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003545 T1 = S.Context.getCanonicalType(T1);
3546 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003547 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003548 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3549 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003550 if (UnqualT1 == UnqualT2) {
John McCallf85e1932011-06-15 23:02:42 +00003551 // Objective-C++ ARC: If the references refer to objects with different
3552 // lifetimes, prefer bindings that don't change lifetime.
3553 if (SCS1.ObjCLifetimeConversionBinding !=
3554 SCS2.ObjCLifetimeConversionBinding) {
3555 return SCS1.ObjCLifetimeConversionBinding
3556 ? ImplicitConversionSequence::Worse
3557 : ImplicitConversionSequence::Better;
3558 }
3559
Chandler Carruth6df868e2010-12-12 08:17:55 +00003560 // If the type is an array type, promote the element qualifiers to the
3561 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003562 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003563 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003564 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003565 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003566 if (T2.isMoreQualifiedThan(T1))
3567 return ImplicitConversionSequence::Better;
3568 else if (T1.isMoreQualifiedThan(T2))
John McCallf85e1932011-06-15 23:02:42 +00003569 return ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003570 }
3571 }
Douglas Gregor57373262008-10-22 14:17:15 +00003572
Francois Pichet1c98d622011-09-18 21:37:37 +00003573 // In Microsoft mode, prefer an integral conversion to a
3574 // floating-to-integral conversion if the integral conversion
3575 // is between types of the same size.
3576 // For example:
3577 // void f(float);
3578 // void f(int);
3579 // int main {
3580 // long a;
3581 // f(a);
3582 // }
3583 // Here, MSVC will call f(int) instead of generating a compile error
3584 // as clang will do in standard mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00003585 if (S.getLangOpts().MicrosoftMode &&
Francois Pichet1c98d622011-09-18 21:37:37 +00003586 SCS1.Second == ICK_Integral_Conversion &&
3587 SCS2.Second == ICK_Floating_Integral &&
3588 S.Context.getTypeSize(SCS1.getFromType()) ==
3589 S.Context.getTypeSize(SCS1.getToType(2)))
3590 return ImplicitConversionSequence::Better;
3591
Douglas Gregor57373262008-10-22 14:17:15 +00003592 return ImplicitConversionSequence::Indistinguishable;
3593}
3594
3595/// CompareQualificationConversions - Compares two standard conversion
3596/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00003597/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3598ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003599CompareQualificationConversions(Sema &S,
3600 const StandardConversionSequence& SCS1,
3601 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00003602 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00003603 // -- S1 and S2 differ only in their qualification conversion and
3604 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3605 // cv-qualification signature of type T1 is a proper subset of
3606 // the cv-qualification signature of type T2, and S1 is not the
3607 // deprecated string literal array-to-pointer conversion (4.2).
3608 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3609 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3610 return ImplicitConversionSequence::Indistinguishable;
3611
3612 // FIXME: the example in the standard doesn't use a qualification
3613 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00003614 QualType T1 = SCS1.getToType(2);
3615 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003616 T1 = S.Context.getCanonicalType(T1);
3617 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003618 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003619 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3620 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00003621
3622 // If the types are the same, we won't learn anything by unwrapped
3623 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003624 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00003625 return ImplicitConversionSequence::Indistinguishable;
3626
Chandler Carruth28e318c2009-12-29 07:16:59 +00003627 // If the type is an array type, promote the element qualifiers to the type
3628 // for comparison.
3629 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003630 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003631 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003632 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003633
Mike Stump1eb44332009-09-09 15:08:12 +00003634 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00003635 = ImplicitConversionSequence::Indistinguishable;
John McCallf85e1932011-06-15 23:02:42 +00003636
3637 // Objective-C++ ARC:
3638 // Prefer qualification conversions not involving a change in lifetime
3639 // to qualification conversions that do not change lifetime.
3640 if (SCS1.QualificationIncludesObjCLifetime !=
3641 SCS2.QualificationIncludesObjCLifetime) {
3642 Result = SCS1.QualificationIncludesObjCLifetime
3643 ? ImplicitConversionSequence::Worse
3644 : ImplicitConversionSequence::Better;
3645 }
3646
John McCall120d63c2010-08-24 20:38:10 +00003647 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00003648 // Within each iteration of the loop, we check the qualifiers to
3649 // determine if this still looks like a qualification
3650 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00003651 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00003652 // until there are no more pointers or pointers-to-members left
3653 // to unwrap. This essentially mimics what
3654 // IsQualificationConversion does, but here we're checking for a
3655 // strict subset of qualifiers.
3656 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3657 // The qualifiers are the same, so this doesn't tell us anything
3658 // about how the sequences rank.
3659 ;
3660 else if (T2.isMoreQualifiedThan(T1)) {
3661 // T1 has fewer qualifiers, so it could be the better sequence.
3662 if (Result == ImplicitConversionSequence::Worse)
3663 // Neither has qualifiers that are a subset of the other's
3664 // qualifiers.
3665 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003666
Douglas Gregor57373262008-10-22 14:17:15 +00003667 Result = ImplicitConversionSequence::Better;
3668 } else if (T1.isMoreQualifiedThan(T2)) {
3669 // T2 has fewer qualifiers, so it could be the better sequence.
3670 if (Result == ImplicitConversionSequence::Better)
3671 // Neither has qualifiers that are a subset of the other's
3672 // qualifiers.
3673 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003674
Douglas Gregor57373262008-10-22 14:17:15 +00003675 Result = ImplicitConversionSequence::Worse;
3676 } else {
3677 // Qualifiers are disjoint.
3678 return ImplicitConversionSequence::Indistinguishable;
3679 }
3680
3681 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00003682 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00003683 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003684 }
3685
Douglas Gregor57373262008-10-22 14:17:15 +00003686 // Check that the winning standard conversion sequence isn't using
3687 // the deprecated string literal array to pointer conversion.
3688 switch (Result) {
3689 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00003690 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003691 Result = ImplicitConversionSequence::Indistinguishable;
3692 break;
3693
3694 case ImplicitConversionSequence::Indistinguishable:
3695 break;
3696
3697 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00003698 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003699 Result = ImplicitConversionSequence::Indistinguishable;
3700 break;
3701 }
3702
3703 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003704}
3705
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003706/// CompareDerivedToBaseConversions - Compares two standard conversion
3707/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00003708/// various kinds of derived-to-base conversions (C++
3709/// [over.ics.rank]p4b3). As part of these checks, we also look at
3710/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003711ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003712CompareDerivedToBaseConversions(Sema &S,
3713 const StandardConversionSequence& SCS1,
3714 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00003715 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003716 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00003717 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003718 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003719
3720 // Adjust the types we're converting from via the array-to-pointer
3721 // conversion, if we need to.
3722 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003723 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003724 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003725 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003726
3727 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00003728 FromType1 = S.Context.getCanonicalType(FromType1);
3729 ToType1 = S.Context.getCanonicalType(ToType1);
3730 FromType2 = S.Context.getCanonicalType(FromType2);
3731 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003732
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003733 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003734 //
3735 // If class B is derived directly or indirectly from class A and
3736 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00003737 //
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003738 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00003739 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00003740 SCS2.Second == ICK_Pointer_Conversion &&
3741 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3742 FromType1->isPointerType() && FromType2->isPointerType() &&
3743 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003744 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003745 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00003746 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003747 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003748 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003749 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003750 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003751 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00003752
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003753 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003754 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003755 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003756 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003757 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003758 return ImplicitConversionSequence::Worse;
3759 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003760
3761 // -- conversion of B* to A* is better than conversion of C* to A*,
3762 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003763 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003764 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003765 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003766 return ImplicitConversionSequence::Worse;
Douglas Gregor395cc372011-01-31 18:51:41 +00003767 }
3768 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3769 SCS2.Second == ICK_Pointer_Conversion) {
3770 const ObjCObjectPointerType *FromPtr1
3771 = FromType1->getAs<ObjCObjectPointerType>();
3772 const ObjCObjectPointerType *FromPtr2
3773 = FromType2->getAs<ObjCObjectPointerType>();
3774 const ObjCObjectPointerType *ToPtr1
3775 = ToType1->getAs<ObjCObjectPointerType>();
3776 const ObjCObjectPointerType *ToPtr2
3777 = ToType2->getAs<ObjCObjectPointerType>();
3778
3779 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3780 // Apply the same conversion ranking rules for Objective-C pointer types
3781 // that we do for C++ pointers to class types. However, we employ the
3782 // Objective-C pseudo-subtyping relationship used for assignment of
3783 // Objective-C pointer types.
3784 bool FromAssignLeft
3785 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3786 bool FromAssignRight
3787 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3788 bool ToAssignLeft
3789 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3790 bool ToAssignRight
3791 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3792
3793 // A conversion to an a non-id object pointer type or qualified 'id'
3794 // type is better than a conversion to 'id'.
3795 if (ToPtr1->isObjCIdType() &&
3796 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3797 return ImplicitConversionSequence::Worse;
3798 if (ToPtr2->isObjCIdType() &&
3799 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3800 return ImplicitConversionSequence::Better;
3801
3802 // A conversion to a non-id object pointer type is better than a
3803 // conversion to a qualified 'id' type
3804 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3805 return ImplicitConversionSequence::Worse;
3806 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3807 return ImplicitConversionSequence::Better;
3808
3809 // A conversion to an a non-Class object pointer type or qualified 'Class'
3810 // type is better than a conversion to 'Class'.
3811 if (ToPtr1->isObjCClassType() &&
3812 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3813 return ImplicitConversionSequence::Worse;
3814 if (ToPtr2->isObjCClassType() &&
3815 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3816 return ImplicitConversionSequence::Better;
3817
3818 // A conversion to a non-Class object pointer type is better than a
3819 // conversion to a qualified 'Class' type.
3820 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3821 return ImplicitConversionSequence::Worse;
3822 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3823 return ImplicitConversionSequence::Better;
Mike Stump1eb44332009-09-09 15:08:12 +00003824
Douglas Gregor395cc372011-01-31 18:51:41 +00003825 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3826 if (S.Context.hasSameType(FromType1, FromType2) &&
3827 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3828 (ToAssignLeft != ToAssignRight))
3829 return ToAssignLeft? ImplicitConversionSequence::Worse
3830 : ImplicitConversionSequence::Better;
3831
3832 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3833 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3834 (FromAssignLeft != FromAssignRight))
3835 return FromAssignLeft? ImplicitConversionSequence::Better
3836 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003837 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003838 }
Douglas Gregor395cc372011-01-31 18:51:41 +00003839
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003840 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003841 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3842 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3843 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003844 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003845 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003846 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003847 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003848 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003849 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003850 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003851 ToType2->getAs<MemberPointerType>();
3852 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3853 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3854 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3855 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3856 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3857 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3858 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3859 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003860 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003861 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003862 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003863 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00003864 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003865 return ImplicitConversionSequence::Better;
3866 }
3867 // conversion of B::* to C::* is better than conversion of A::* to C::*
3868 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003869 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003870 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003871 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003872 return ImplicitConversionSequence::Worse;
3873 }
3874 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003875
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003876 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00003877 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00003878 // -- binding of an expression of type C to a reference of type
3879 // B& is better than binding an expression of type C to a
3880 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003881 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3882 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3883 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003884 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003885 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003886 return ImplicitConversionSequence::Worse;
3887 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003888
Douglas Gregor225c41e2008-11-03 19:09:14 +00003889 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00003890 // -- binding of an expression of type B to a reference of type
3891 // A& is better than binding an expression of type C to a
3892 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003893 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3894 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3895 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003896 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003897 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003898 return ImplicitConversionSequence::Worse;
3899 }
3900 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003901
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003902 return ImplicitConversionSequence::Indistinguishable;
3903}
3904
Douglas Gregor0162c1c2013-03-26 23:36:30 +00003905/// \brief Determine whether the given type is valid, e.g., it is not an invalid
3906/// C++ class.
3907static bool isTypeValid(QualType T) {
3908 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3909 return !Record->isInvalidDecl();
3910
3911 return true;
3912}
3913
Douglas Gregorabe183d2010-04-13 16:31:36 +00003914/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3915/// determine whether they are reference-related,
3916/// reference-compatible, reference-compatible with added
3917/// qualification, or incompatible, for use in C++ initialization by
3918/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3919/// type, and the first type (T1) is the pointee type of the reference
3920/// type being initialized.
3921Sema::ReferenceCompareResult
3922Sema::CompareReferenceRelationship(SourceLocation Loc,
3923 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00003924 bool &DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003925 bool &ObjCConversion,
3926 bool &ObjCLifetimeConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003927 assert(!OrigT1->isReferenceType() &&
3928 "T1 must be the pointee type of the reference type");
3929 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3930
3931 QualType T1 = Context.getCanonicalType(OrigT1);
3932 QualType T2 = Context.getCanonicalType(OrigT2);
3933 Qualifiers T1Quals, T2Quals;
3934 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3935 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3936
3937 // C++ [dcl.init.ref]p4:
3938 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3939 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3940 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00003941 DerivedToBase = false;
3942 ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003943 ObjCLifetimeConversion = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003944 if (UnqualT1 == UnqualT2) {
3945 // Nothing to do.
Douglas Gregord10099e2012-05-04 16:32:21 +00003946 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor0162c1c2013-03-26 23:36:30 +00003947 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
3948 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregorabe183d2010-04-13 16:31:36 +00003949 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00003950 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3951 UnqualT2->isObjCObjectOrInterfaceType() &&
3952 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3953 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003954 else
3955 return Ref_Incompatible;
3956
3957 // At this point, we know that T1 and T2 are reference-related (at
3958 // least).
3959
3960 // If the type is an array type, promote the element qualifiers to the type
3961 // for comparison.
3962 if (isa<ArrayType>(T1) && T1Quals)
3963 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3964 if (isa<ArrayType>(T2) && T2Quals)
3965 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3966
3967 // C++ [dcl.init.ref]p4:
3968 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3969 // reference-related to T2 and cv1 is the same cv-qualification
3970 // as, or greater cv-qualification than, cv2. For purposes of
3971 // overload resolution, cases for which cv1 is greater
3972 // cv-qualification than cv2 are identified as
3973 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003974 //
3975 // Note that we also require equivalence of Objective-C GC and address-space
3976 // qualifiers when performing these computations, so that e.g., an int in
3977 // address space 1 is not reference-compatible with an int in address
3978 // space 2.
John McCallf85e1932011-06-15 23:02:42 +00003979 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3980 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3981 T1Quals.removeObjCLifetime();
3982 T2Quals.removeObjCLifetime();
3983 ObjCLifetimeConversion = true;
3984 }
3985
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003986 if (T1Quals == T2Quals)
Douglas Gregorabe183d2010-04-13 16:31:36 +00003987 return Ref_Compatible;
John McCallf85e1932011-06-15 23:02:42 +00003988 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregorabe183d2010-04-13 16:31:36 +00003989 return Ref_Compatible_With_Added_Qualification;
3990 else
3991 return Ref_Related;
3992}
3993
Douglas Gregor604eb652010-08-11 02:15:33 +00003994/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00003995/// with DeclType. Return true if something definite is found.
3996static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00003997FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3998 QualType DeclType, SourceLocation DeclLoc,
3999 Expr *Init, QualType T2, bool AllowRvalues,
4000 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004001 assert(T2->isRecordType() && "Can only find conversions of record types.");
4002 CXXRecordDecl *T2RecordDecl
4003 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4004
4005 OverloadCandidateSet CandidateSet(DeclLoc);
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00004006 std::pair<CXXRecordDecl::conversion_iterator,
4007 CXXRecordDecl::conversion_iterator>
4008 Conversions = T2RecordDecl->getVisibleConversionFunctions();
4009 for (CXXRecordDecl::conversion_iterator
4010 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004011 NamedDecl *D = *I;
4012 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4013 if (isa<UsingShadowDecl>(D))
4014 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4015
4016 FunctionTemplateDecl *ConvTemplate
4017 = dyn_cast<FunctionTemplateDecl>(D);
4018 CXXConversionDecl *Conv;
4019 if (ConvTemplate)
4020 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4021 else
4022 Conv = cast<CXXConversionDecl>(D);
4023
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004024 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor604eb652010-08-11 02:15:33 +00004025 // explicit conversions, skip it.
4026 if (!AllowExplicit && Conv->isExplicit())
4027 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004028
Douglas Gregor604eb652010-08-11 02:15:33 +00004029 if (AllowRvalues) {
4030 bool DerivedToBase = false;
4031 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004032 bool ObjCLifetimeConversion = false;
Douglas Gregor203050c2011-10-04 23:59:32 +00004033
4034 // If we are initializing an rvalue reference, don't permit conversion
4035 // functions that return lvalues.
4036 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4037 const ReferenceType *RefType
4038 = Conv->getConversionType()->getAs<LValueReferenceType>();
4039 if (RefType && !RefType->getPointeeType()->isFunctionType())
4040 continue;
4041 }
4042
Douglas Gregor604eb652010-08-11 02:15:33 +00004043 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00004044 S.CompareReferenceRelationship(
4045 DeclLoc,
4046 Conv->getConversionType().getNonReferenceType()
4047 .getUnqualifiedType(),
4048 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCallf85e1932011-06-15 23:02:42 +00004049 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth6df868e2010-12-12 08:17:55 +00004050 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-08-11 02:15:33 +00004051 continue;
4052 } else {
4053 // If the conversion function doesn't return a reference type,
4054 // it can't be considered for this conversion. An rvalue reference
4055 // is only acceptable if its referencee is a function type.
4056
4057 const ReferenceType *RefType =
4058 Conv->getConversionType()->getAs<ReferenceType>();
4059 if (!RefType ||
4060 (!RefType->isLValueReferenceType() &&
4061 !RefType->getPointeeType()->isFunctionType()))
4062 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004063 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004064
Douglas Gregor604eb652010-08-11 02:15:33 +00004065 if (ConvTemplate)
4066 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004067 Init, DeclType, CandidateSet);
Douglas Gregor604eb652010-08-11 02:15:33 +00004068 else
4069 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004070 DeclType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00004071 }
4072
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004073 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4074
Sebastian Redl4680bf22010-06-30 18:13:39 +00004075 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004076 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004077 case OR_Success:
4078 // C++ [over.ics.ref]p1:
4079 //
4080 // [...] If the parameter binds directly to the result of
4081 // applying a conversion function to the argument
4082 // expression, the implicit conversion sequence is a
4083 // user-defined conversion sequence (13.3.3.1.2), with the
4084 // second standard conversion sequence either an identity
4085 // conversion or, if the conversion function returns an
4086 // entity of a type that is a derived class of the parameter
4087 // type, a derived-to-base Conversion.
4088 if (!Best->FinalConversion.DirectBinding)
4089 return false;
4090
4091 ICS.setUserDefined();
4092 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4093 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004094 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004095 ICS.UserDefined.ConversionFunction = Best->Function;
John McCallca82a822011-09-21 08:36:56 +00004096 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004097 ICS.UserDefined.EllipsisConversion = false;
4098 assert(ICS.UserDefined.After.ReferenceBinding &&
4099 ICS.UserDefined.After.DirectBinding &&
4100 "Expected a direct reference binding!");
4101 return true;
4102
4103 case OR_Ambiguous:
4104 ICS.setAmbiguous();
4105 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4106 Cand != CandidateSet.end(); ++Cand)
4107 if (Cand->Viable)
4108 ICS.Ambiguous.addConversion(Cand->Function);
4109 return true;
4110
4111 case OR_No_Viable_Function:
4112 case OR_Deleted:
4113 // There was no suitable conversion, or we found a deleted
4114 // conversion; continue with other checks.
4115 return false;
4116 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004117
David Blaikie7530c032012-01-17 06:56:22 +00004118 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redl4680bf22010-06-30 18:13:39 +00004119}
4120
Douglas Gregorabe183d2010-04-13 16:31:36 +00004121/// \brief Compute an implicit conversion sequence for reference
4122/// initialization.
4123static ImplicitConversionSequence
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004124TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004125 SourceLocation DeclLoc,
4126 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00004127 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004128 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4129
4130 // Most paths end in a failed conversion.
4131 ImplicitConversionSequence ICS;
4132 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4133
4134 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4135 QualType T2 = Init->getType();
4136
4137 // If the initializer is the address of an overloaded function, try
4138 // to resolve the overloaded function. If all goes well, T2 is the
4139 // type of the resulting function.
4140 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4141 DeclAccessPair Found;
4142 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4143 false, Found))
4144 T2 = Fn->getType();
4145 }
4146
4147 // Compute some basic properties of the types and the initializer.
4148 bool isRValRef = DeclType->isRValueReferenceType();
4149 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00004150 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004151 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004152 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004153 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00004154 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00004155 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004156
Douglas Gregorabe183d2010-04-13 16:31:36 +00004157
Sebastian Redl4680bf22010-06-30 18:13:39 +00004158 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00004159 // A reference to type "cv1 T1" is initialized by an expression
4160 // of type "cv2 T2" as follows:
4161
Sebastian Redl4680bf22010-06-30 18:13:39 +00004162 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004163 if (!isRValRef) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004164 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4165 // reference-compatible with "cv2 T2," or
4166 //
4167 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4168 if (InitCategory.isLValue() &&
4169 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004170 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00004171 // When a parameter of reference type binds directly (8.5.3)
4172 // to an argument expression, the implicit conversion sequence
4173 // is the identity conversion, unless the argument expression
4174 // has a type that is a derived class of the parameter type,
4175 // in which case the implicit conversion sequence is a
4176 // derived-to-base Conversion (13.3.3.1).
4177 ICS.setStandard();
4178 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00004179 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4180 : ObjCConversion? ICK_Compatible_Conversion
4181 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004182 ICS.Standard.Third = ICK_Identity;
4183 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4184 ICS.Standard.setToType(0, T2);
4185 ICS.Standard.setToType(1, T1);
4186 ICS.Standard.setToType(2, T1);
4187 ICS.Standard.ReferenceBinding = true;
4188 ICS.Standard.DirectBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004189 ICS.Standard.IsLvalueReference = !isRValRef;
4190 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4191 ICS.Standard.BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004192 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004193 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004194 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004195
Sebastian Redl4680bf22010-06-30 18:13:39 +00004196 // Nothing more to do: the inaccessibility/ambiguity check for
4197 // derived-to-base conversions is suppressed when we're
4198 // computing the implicit conversion sequence (C++
4199 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00004200 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004201 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00004202
Sebastian Redl4680bf22010-06-30 18:13:39 +00004203 // -- has a class type (i.e., T2 is a class type), where T1 is
4204 // not reference-related to T2, and can be implicitly
4205 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4206 // is reference-compatible with "cv3 T3" 92) (this
4207 // conversion is selected by enumerating the applicable
4208 // conversion functions (13.3.1.6) and choosing the best
4209 // one through overload resolution (13.3)),
4210 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004211 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redl4680bf22010-06-30 18:13:39 +00004212 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00004213 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4214 Init, T2, /*AllowRvalues=*/false,
4215 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00004216 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004217 }
4218 }
4219
Sebastian Redl4680bf22010-06-30 18:13:39 +00004220 // -- Otherwise, the reference shall be an lvalue reference to a
4221 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004222 // shall be an rvalue reference.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004223 //
Douglas Gregor66821b52010-04-18 09:22:00 +00004224 // We actually handle one oddity of C++ [over.ics.ref] at this
4225 // point, which is that, due to p2 (which short-circuits reference
4226 // binding by only attempting a simple conversion for non-direct
4227 // bindings) and p3's strange wording, we allow a const volatile
4228 // reference to bind to an rvalue. Hence the check for the presence
4229 // of "const" rather than checking for "const" being the only
4230 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00004231 // This is also the point where rvalue references and lvalue inits no longer
4232 // go together.
Richard Smith8ab10aa2012-05-24 04:29:20 +00004233 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregorabe183d2010-04-13 16:31:36 +00004234 return ICS;
4235
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004236 // -- If the initializer expression
4237 //
4238 // -- is an xvalue, class prvalue, array prvalue or function
John McCallf85e1932011-06-15 23:02:42 +00004239 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004240 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4241 (InitCategory.isXValue() ||
4242 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4243 (InitCategory.isLValue() && T2->isFunctionType()))) {
4244 ICS.setStandard();
4245 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004246 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004247 : ObjCConversion? ICK_Compatible_Conversion
4248 : ICK_Identity;
4249 ICS.Standard.Third = ICK_Identity;
4250 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4251 ICS.Standard.setToType(0, T2);
4252 ICS.Standard.setToType(1, T1);
4253 ICS.Standard.setToType(2, T1);
4254 ICS.Standard.ReferenceBinding = true;
4255 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4256 // binding unless we're binding to a class prvalue.
4257 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4258 // allow the use of rvalue references in C++98/03 for the benefit of
4259 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004260 ICS.Standard.DirectBinding =
Richard Smith80ad52f2013-01-02 11:42:31 +00004261 S.getLangOpts().CPlusPlus11 ||
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004262 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregor440a4832011-01-26 14:52:12 +00004263 ICS.Standard.IsLvalueReference = !isRValRef;
4264 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004265 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004266 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004267 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004268 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004269 return ICS;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004270 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004271
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004272 // -- has a class type (i.e., T2 is a class type), where T1 is not
4273 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004274 // an xvalue, class prvalue, or function lvalue of type
4275 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004276 // "cv3 T3",
4277 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004278 // then the reference is bound to the value of the initializer
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004279 // expression in the first case and to the result of the conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004280 // in the second case (or, in either case, to an appropriate base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004281 // class subobject).
4282 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004283 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004284 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4285 Init, T2, /*AllowRvalues=*/true,
4286 AllowExplicit)) {
4287 // In the second case, if the reference is an rvalue reference
4288 // and the second standard conversion sequence of the
4289 // user-defined conversion sequence includes an lvalue-to-rvalue
4290 // conversion, the program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004291 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004292 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4293 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4294
Douglas Gregor68ed68b2011-01-21 16:36:05 +00004295 return ICS;
Rafael Espindolaaa5952c2011-01-22 15:32:35 +00004296 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004297
Douglas Gregorabe183d2010-04-13 16:31:36 +00004298 // -- Otherwise, a temporary of type "cv1 T1" is created and
4299 // initialized from the initializer expression using the
4300 // rules for a non-reference copy initialization (8.5). The
4301 // reference is then bound to the temporary. If T1 is
4302 // reference-related to T2, cv1 must be the same
4303 // cv-qualification as, or greater cv-qualification than,
4304 // cv2; otherwise, the program is ill-formed.
4305 if (RefRelationship == Sema::Ref_Related) {
4306 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4307 // we would be reference-compatible or reference-compatible with
4308 // added qualification. But that wasn't the case, so the reference
4309 // initialization fails.
John McCallf85e1932011-06-15 23:02:42 +00004310 //
4311 // Note that we only want to check address spaces and cvr-qualifiers here.
4312 // ObjC GC and lifetime qualifiers aren't important.
4313 Qualifiers T1Quals = T1.getQualifiers();
4314 Qualifiers T2Quals = T2.getQualifiers();
4315 T1Quals.removeObjCGCAttr();
4316 T1Quals.removeObjCLifetime();
4317 T2Quals.removeObjCGCAttr();
4318 T2Quals.removeObjCLifetime();
4319 if (!T1Quals.compatiblyIncludes(T2Quals))
4320 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004321 }
4322
4323 // If at least one of the types is a class type, the types are not
4324 // related, and we aren't allowed any user conversions, the
4325 // reference binding fails. This case is important for breaking
4326 // recursion, since TryImplicitConversion below will attempt to
4327 // create a temporary through the use of a copy constructor.
4328 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4329 (T1->isRecordType() || T2->isRecordType()))
4330 return ICS;
4331
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004332 // If T1 is reference-related to T2 and the reference is an rvalue
4333 // reference, the initializer expression shall not be an lvalue.
4334 if (RefRelationship >= Sema::Ref_Related &&
4335 isRValRef && Init->Classify(S.Context).isLValue())
4336 return ICS;
4337
Douglas Gregorabe183d2010-04-13 16:31:36 +00004338 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00004339 // When a parameter of reference type is not bound directly to
4340 // an argument expression, the conversion sequence is the one
4341 // required to convert the argument expression to the
4342 // underlying type of the reference according to
4343 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4344 // to copy-initializing a temporary of the underlying type with
4345 // the argument expression. Any difference in top-level
4346 // cv-qualification is subsumed by the initialization itself
4347 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00004348 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4349 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004350 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004351 /*CStyle=*/false,
4352 /*AllowObjCWritebackConversion=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004353
4354 // Of course, that's still a reference binding.
4355 if (ICS.isStandard()) {
4356 ICS.Standard.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004357 ICS.Standard.IsLvalueReference = !isRValRef;
4358 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4359 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004360 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004361 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004362 } else if (ICS.isUserDefined()) {
Douglas Gregor203050c2011-10-04 23:59:32 +00004363 // Don't allow rvalue references to bind to lvalues.
4364 if (DeclType->isRValueReferenceType()) {
4365 if (const ReferenceType *RefType
4366 = ICS.UserDefined.ConversionFunction->getResultType()
4367 ->getAs<LValueReferenceType>()) {
4368 if (!RefType->getPointeeType()->isFunctionType()) {
4369 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4370 DeclType);
4371 return ICS;
4372 }
4373 }
4374 }
4375
Douglas Gregorabe183d2010-04-13 16:31:36 +00004376 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregorf20d2722011-08-15 13:59:46 +00004377 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4378 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4379 ICS.UserDefined.After.BindsToRvalue = true;
4380 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4381 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004382 }
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004383
Douglas Gregorabe183d2010-04-13 16:31:36 +00004384 return ICS;
4385}
4386
Sebastian Redl5405b812011-10-16 18:19:34 +00004387static ImplicitConversionSequence
4388TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4389 bool SuppressUserConversions,
4390 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004391 bool AllowObjCWritebackConversion,
4392 bool AllowExplicit = false);
Sebastian Redl5405b812011-10-16 18:19:34 +00004393
4394/// TryListConversion - Try to copy-initialize a value of type ToType from the
4395/// initializer list From.
4396static ImplicitConversionSequence
4397TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4398 bool SuppressUserConversions,
4399 bool InOverloadResolution,
4400 bool AllowObjCWritebackConversion) {
4401 // C++11 [over.ics.list]p1:
4402 // When an argument is an initializer list, it is not an expression and
4403 // special rules apply for converting it to a parameter type.
4404
4405 ImplicitConversionSequence Result;
4406 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004407 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004408
Sebastian Redlb832f6d2012-01-23 22:09:39 +00004409 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redlfe592282012-01-17 22:49:48 +00004410 // initialized from init lists.
Douglas Gregord10099e2012-05-04 16:32:21 +00004411 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redlfe592282012-01-17 22:49:48 +00004412 return Result;
4413
Sebastian Redl5405b812011-10-16 18:19:34 +00004414 // C++11 [over.ics.list]p2:
4415 // If the parameter type is std::initializer_list<X> or "array of X" and
4416 // all the elements can be implicitly converted to X, the implicit
4417 // conversion sequence is the worst conversion necessary to convert an
4418 // element of the list to X.
Sebastian Redladfb5352012-02-27 22:38:26 +00004419 bool toStdInitializerList = false;
Sebastian Redlfe592282012-01-17 22:49:48 +00004420 QualType X;
Sebastian Redl5405b812011-10-16 18:19:34 +00004421 if (ToType->isArrayType())
Richard Smith2801d9a2012-12-09 06:48:56 +00004422 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redlfe592282012-01-17 22:49:48 +00004423 else
Sebastian Redladfb5352012-02-27 22:38:26 +00004424 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redlfe592282012-01-17 22:49:48 +00004425 if (!X.isNull()) {
4426 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4427 Expr *Init = From->getInit(i);
4428 ImplicitConversionSequence ICS =
4429 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4430 InOverloadResolution,
4431 AllowObjCWritebackConversion);
4432 // If a single element isn't convertible, fail.
4433 if (ICS.isBad()) {
4434 Result = ICS;
4435 break;
4436 }
4437 // Otherwise, look for the worst conversion.
4438 if (Result.isBad() ||
4439 CompareImplicitConversionSequences(S, ICS, Result) ==
4440 ImplicitConversionSequence::Worse)
4441 Result = ICS;
4442 }
Douglas Gregor5b4bf132012-04-04 23:09:20 +00004443
4444 // For an empty list, we won't have computed any conversion sequence.
4445 // Introduce the identity conversion sequence.
4446 if (From->getNumInits() == 0) {
4447 Result.setStandard();
4448 Result.Standard.setAsIdentityConversion();
4449 Result.Standard.setFromType(ToType);
4450 Result.Standard.setAllToTypes(ToType);
4451 }
4452
Sebastian Redlfe592282012-01-17 22:49:48 +00004453 Result.setListInitializationSequence();
Sebastian Redladfb5352012-02-27 22:38:26 +00004454 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redl5405b812011-10-16 18:19:34 +00004455 return Result;
Sebastian Redlfe592282012-01-17 22:49:48 +00004456 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004457
4458 // C++11 [over.ics.list]p3:
4459 // Otherwise, if the parameter is a non-aggregate class X and overload
4460 // resolution chooses a single best constructor [...] the implicit
4461 // conversion sequence is a user-defined conversion sequence. If multiple
4462 // constructors are viable but none is better than the others, the
4463 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004464 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4465 // This function can deal with initializer lists.
4466 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4467 /*AllowExplicit=*/false,
4468 InOverloadResolution, /*CStyle=*/false,
4469 AllowObjCWritebackConversion);
4470 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004471 return Result;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004472 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004473
4474 // C++11 [over.ics.list]p4:
4475 // Otherwise, if the parameter has an aggregate type which can be
4476 // initialized from the initializer list [...] the implicit conversion
4477 // sequence is a user-defined conversion sequence.
Sebastian Redl5405b812011-10-16 18:19:34 +00004478 if (ToType->isAggregateType()) {
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004479 // Type is an aggregate, argument is an init list. At this point it comes
4480 // down to checking whether the initialization works.
4481 // FIXME: Find out whether this parameter is consumed or not.
4482 InitializedEntity Entity =
4483 InitializedEntity::InitializeParameter(S.Context, ToType,
4484 /*Consumed=*/false);
4485 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4486 Result.setUserDefined();
4487 Result.UserDefined.Before.setAsIdentityConversion();
4488 // Initializer lists don't have a type.
4489 Result.UserDefined.Before.setFromType(QualType());
4490 Result.UserDefined.Before.setAllToTypes(QualType());
4491
4492 Result.UserDefined.After.setAsIdentityConversion();
4493 Result.UserDefined.After.setFromType(ToType);
4494 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramer83db10e2012-02-02 19:35:29 +00004495 Result.UserDefined.ConversionFunction = 0;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004496 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004497 return Result;
4498 }
4499
4500 // C++11 [over.ics.list]p5:
4501 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004502 if (ToType->isReferenceType()) {
4503 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4504 // mention initializer lists in any way. So we go by what list-
4505 // initialization would do and try to extrapolate from that.
4506
4507 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4508
4509 // If the initializer list has a single element that is reference-related
4510 // to the parameter type, we initialize the reference from that.
4511 if (From->getNumInits() == 1) {
4512 Expr *Init = From->getInit(0);
4513
4514 QualType T2 = Init->getType();
4515
4516 // If the initializer is the address of an overloaded function, try
4517 // to resolve the overloaded function. If all goes well, T2 is the
4518 // type of the resulting function.
4519 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4520 DeclAccessPair Found;
4521 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4522 Init, ToType, false, Found))
4523 T2 = Fn->getType();
4524 }
4525
4526 // Compute some basic properties of the types and the initializer.
4527 bool dummy1 = false;
4528 bool dummy2 = false;
4529 bool dummy3 = false;
4530 Sema::ReferenceCompareResult RefRelationship
4531 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4532 dummy2, dummy3);
4533
4534 if (RefRelationship >= Sema::Ref_Related)
4535 return TryReferenceInit(S, Init, ToType,
4536 /*FIXME:*/From->getLocStart(),
4537 SuppressUserConversions,
4538 /*AllowExplicit=*/false);
4539 }
4540
4541 // Otherwise, we bind the reference to a temporary created from the
4542 // initializer list.
4543 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4544 InOverloadResolution,
4545 AllowObjCWritebackConversion);
4546 if (Result.isFailure())
4547 return Result;
4548 assert(!Result.isEllipsis() &&
4549 "Sub-initialization cannot result in ellipsis conversion.");
4550
4551 // Can we even bind to a temporary?
4552 if (ToType->isRValueReferenceType() ||
4553 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4554 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4555 Result.UserDefined.After;
4556 SCS.ReferenceBinding = true;
4557 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4558 SCS.BindsToRvalue = true;
4559 SCS.BindsToFunctionLvalue = false;
4560 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4561 SCS.ObjCLifetimeConversionBinding = false;
4562 } else
4563 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4564 From, ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004565 return Result;
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004566 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004567
4568 // C++11 [over.ics.list]p6:
4569 // Otherwise, if the parameter type is not a class:
4570 if (!ToType->isRecordType()) {
4571 // - if the initializer list has one element, the implicit conversion
4572 // sequence is the one required to convert the element to the
4573 // parameter type.
Sebastian Redl5405b812011-10-16 18:19:34 +00004574 unsigned NumInits = From->getNumInits();
4575 if (NumInits == 1)
4576 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4577 SuppressUserConversions,
4578 InOverloadResolution,
4579 AllowObjCWritebackConversion);
4580 // - if the initializer list has no elements, the implicit conversion
4581 // sequence is the identity conversion.
4582 else if (NumInits == 0) {
4583 Result.setStandard();
4584 Result.Standard.setAsIdentityConversion();
John McCalle14ba2c2012-04-04 02:40:27 +00004585 Result.Standard.setFromType(ToType);
4586 Result.Standard.setAllToTypes(ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004587 }
Sebastian Redl2422e822012-02-28 23:36:38 +00004588 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004589 return Result;
4590 }
4591
4592 // C++11 [over.ics.list]p7:
4593 // In all cases other than those enumerated above, no conversion is possible
4594 return Result;
4595}
4596
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004597/// TryCopyInitialization - Try to copy-initialize a value of type
4598/// ToType from the expression From. Return the implicit conversion
4599/// sequence required to pass this argument, which may be a bad
4600/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00004601/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00004602/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00004603static ImplicitConversionSequence
4604TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004605 bool SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004606 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004607 bool AllowObjCWritebackConversion,
4608 bool AllowExplicit) {
Sebastian Redl5405b812011-10-16 18:19:34 +00004609 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4610 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4611 InOverloadResolution,AllowObjCWritebackConversion);
4612
Douglas Gregorabe183d2010-04-13 16:31:36 +00004613 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00004614 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004615 /*FIXME:*/From->getLocStart(),
4616 SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00004617 AllowExplicit);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004618
John McCall120d63c2010-08-24 20:38:10 +00004619 return TryImplicitConversion(S, From, ToType,
4620 SuppressUserConversions,
4621 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004622 InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00004623 /*CStyle=*/false,
4624 AllowObjCWritebackConversion);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004625}
4626
Anna Zaksf3546ee2011-07-28 19:46:48 +00004627static bool TryCopyInitialization(const CanQualType FromQTy,
4628 const CanQualType ToQTy,
4629 Sema &S,
4630 SourceLocation Loc,
4631 ExprValueKind FromVK) {
4632 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4633 ImplicitConversionSequence ICS =
4634 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4635
4636 return !ICS.isBad();
4637}
4638
Douglas Gregor96176b32008-11-18 23:14:02 +00004639/// TryObjectArgumentInitialization - Try to initialize the object
4640/// parameter of the given member function (@c Method) from the
4641/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00004642static ImplicitConversionSequence
Richard Smith98bfbf52013-01-26 02:07:32 +00004643TryObjectArgumentInitialization(Sema &S, QualType FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004644 Expr::Classification FromClassification,
John McCall120d63c2010-08-24 20:38:10 +00004645 CXXMethodDecl *Method,
4646 CXXRecordDecl *ActingContext) {
4647 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00004648 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4649 // const volatile object.
4650 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4651 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00004652 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00004653
4654 // Set up the conversion sequence as a "bad" conversion, to allow us
4655 // to exit early.
4656 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00004657
4658 // We need to have an object of class type.
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004659 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004660 FromType = PT->getPointeeType();
4661
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004662 // When we had a pointer, it's implicitly dereferenced, so we
4663 // better have an lvalue.
4664 assert(FromClassification.isLValue());
4665 }
4666
Anders Carlssona552f7c2009-05-01 18:34:30 +00004667 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00004668
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004669 // C++0x [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004670 // For non-static member functions, the type of the implicit object
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004671 // parameter is
4672 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004673 // - "lvalue reference to cv X" for functions declared without a
4674 // ref-qualifier or with the & ref-qualifier
4675 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004676 // ref-qualifier
4677 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004678 // where X is the class of which the function is a member and cv is the
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004679 // cv-qualification on the member function declaration.
4680 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004681 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004682 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00004683 // (C++ [over.match.funcs]p5). We perform a simplified version of
4684 // reference binding here, that allows class rvalues to bind to
4685 // non-constant references.
4686
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004687 // First check the qualifiers.
John McCall120d63c2010-08-24 20:38:10 +00004688 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004689 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregora4923eb2009-11-16 21:35:15 +00004690 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00004691 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00004692 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith98bfbf52013-01-26 02:07:32 +00004693 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004694 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004695 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004696
4697 // Check that we have either the same type or a derived type. It
4698 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00004699 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00004700 ImplicitConversionKind SecondKind;
4701 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4702 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00004703 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00004704 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00004705 else {
John McCallb1bdc622010-02-25 01:37:24 +00004706 ICS.setBad(BadConversionSequence::unrelated_class,
4707 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004708 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004709 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004710
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004711 // Check the ref-qualifier.
4712 switch (Method->getRefQualifier()) {
4713 case RQ_None:
4714 // Do nothing; we don't care about lvalueness or rvalueness.
4715 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004716
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004717 case RQ_LValue:
4718 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4719 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004720 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004721 ImplicitParamType);
4722 return ICS;
4723 }
4724 break;
4725
4726 case RQ_RValue:
4727 if (!FromClassification.isRValue()) {
4728 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004729 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004730 ImplicitParamType);
4731 return ICS;
4732 }
4733 break;
4734 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004735
Douglas Gregor96176b32008-11-18 23:14:02 +00004736 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004737 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00004738 ICS.Standard.setAsIdentityConversion();
4739 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00004740 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004741 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004742 ICS.Standard.ReferenceBinding = true;
4743 ICS.Standard.DirectBinding = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004744 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregor440a4832011-01-26 14:52:12 +00004745 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004746 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4747 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4748 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor96176b32008-11-18 23:14:02 +00004749 return ICS;
4750}
4751
4752/// PerformObjectArgumentInitialization - Perform initialization of
4753/// the implicit object parameter for the given Method with the given
4754/// expression.
John Wiegley429bb272011-04-08 18:41:53 +00004755ExprResult
4756Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004757 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00004758 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00004759 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004760 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00004761 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00004762 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004763
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004764 Expr::Classification FromClassification;
Ted Kremenek6217b802009-07-29 21:53:49 +00004765 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004766 FromRecordType = PT->getPointeeType();
4767 DestType = Method->getThisType(Context);
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004768 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004769 } else {
4770 FromRecordType = From->getType();
4771 DestType = ImplicitParamRecordType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004772 FromClassification = From->Classify(Context);
Anders Carlssona552f7c2009-05-01 18:34:30 +00004773 }
4774
John McCall701c89e2009-12-03 04:06:58 +00004775 // Note that we always use the true parent context when performing
4776 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004777 ImplicitConversionSequence ICS
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004778 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4779 Method, Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004780 if (ICS.isBad()) {
4781 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4782 Qualifiers FromQs = FromRecordType.getQualifiers();
4783 Qualifiers ToQs = DestType.getQualifiers();
4784 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4785 if (CVR) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004786 Diag(From->getLocStart(),
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004787 diag::err_member_function_call_bad_cvr)
4788 << Method->getDeclName() << FromRecordType << (CVR - 1)
4789 << From->getSourceRange();
4790 Diag(Method->getLocation(), diag::note_previous_decl)
4791 << Method->getDeclName();
John Wiegley429bb272011-04-08 18:41:53 +00004792 return ExprError();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004793 }
4794 }
4795
Daniel Dunbar96a00142012-03-09 18:35:03 +00004796 return Diag(From->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004797 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00004798 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004799 }
Mike Stump1eb44332009-09-09 15:08:12 +00004800
John Wiegley429bb272011-04-08 18:41:53 +00004801 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4802 ExprResult FromRes =
4803 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4804 if (FromRes.isInvalid())
4805 return ExprError();
4806 From = FromRes.take();
4807 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004808
Douglas Gregor5fccd362010-03-03 23:55:11 +00004809 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley429bb272011-04-08 18:41:53 +00004810 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smithacdfa4d2011-11-10 23:32:36 +00004811 From->getValueKind()).take();
John Wiegley429bb272011-04-08 18:41:53 +00004812 return Owned(From);
Douglas Gregor96176b32008-11-18 23:14:02 +00004813}
4814
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004815/// TryContextuallyConvertToBool - Attempt to contextually convert the
4816/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00004817static ImplicitConversionSequence
4818TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00004819 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00004820 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004821 // FIXME: Are these flags correct?
4822 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00004823 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004824 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004825 /*CStyle=*/false,
4826 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004827}
4828
4829/// PerformContextuallyConvertToBool - Perform a contextual conversion
4830/// of the expression From to bool (C++0x [conv]p3).
John Wiegley429bb272011-04-08 18:41:53 +00004831ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004832 if (checkPlaceholderForOverload(*this, From))
4833 return ExprError();
4834
John McCall120d63c2010-08-24 20:38:10 +00004835 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00004836 if (!ICS.isBad())
4837 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004838
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00004839 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004840 return Diag(From->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +00004841 diag::err_typecheck_bool_condition)
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00004842 << From->getType() << From->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004843 return ExprError();
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004844}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004845
Richard Smith8ef7b202012-01-18 23:55:52 +00004846/// Check that the specified conversion is permitted in a converted constant
4847/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4848/// is acceptable.
4849static bool CheckConvertedConstantConversions(Sema &S,
4850 StandardConversionSequence &SCS) {
4851 // Since we know that the target type is an integral or unscoped enumeration
4852 // type, most conversion kinds are impossible. All possible First and Third
4853 // conversions are fine.
4854 switch (SCS.Second) {
4855 case ICK_Identity:
4856 case ICK_Integral_Promotion:
4857 case ICK_Integral_Conversion:
Guy Benyei6959acd2013-02-07 16:05:33 +00004858 case ICK_Zero_Event_Conversion:
Richard Smith8ef7b202012-01-18 23:55:52 +00004859 return true;
4860
4861 case ICK_Boolean_Conversion:
Richard Smith2bcb9842012-09-13 22:00:12 +00004862 // Conversion from an integral or unscoped enumeration type to bool is
4863 // classified as ICK_Boolean_Conversion, but it's also an integral
4864 // conversion, so it's permitted in a converted constant expression.
4865 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4866 SCS.getToType(2)->isBooleanType();
4867
Richard Smith8ef7b202012-01-18 23:55:52 +00004868 case ICK_Floating_Integral:
4869 case ICK_Complex_Real:
4870 return false;
4871
4872 case ICK_Lvalue_To_Rvalue:
4873 case ICK_Array_To_Pointer:
4874 case ICK_Function_To_Pointer:
4875 case ICK_NoReturn_Adjustment:
4876 case ICK_Qualification:
4877 case ICK_Compatible_Conversion:
4878 case ICK_Vector_Conversion:
4879 case ICK_Vector_Splat:
4880 case ICK_Derived_To_Base:
4881 case ICK_Pointer_Conversion:
4882 case ICK_Pointer_Member:
4883 case ICK_Block_Pointer_Conversion:
4884 case ICK_Writeback_Conversion:
4885 case ICK_Floating_Promotion:
4886 case ICK_Complex_Promotion:
4887 case ICK_Complex_Conversion:
4888 case ICK_Floating_Conversion:
4889 case ICK_TransparentUnionConversion:
4890 llvm_unreachable("unexpected second conversion kind");
4891
4892 case ICK_Num_Conversion_Kinds:
4893 break;
4894 }
4895
4896 llvm_unreachable("unknown conversion kind");
4897}
4898
4899/// CheckConvertedConstantExpression - Check that the expression From is a
4900/// converted constant expression of type T, perform the conversion and produce
4901/// the converted expression, per C++11 [expr.const]p3.
4902ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4903 llvm::APSInt &Value,
4904 CCEKind CCE) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004905 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
Richard Smith8ef7b202012-01-18 23:55:52 +00004906 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4907
4908 if (checkPlaceholderForOverload(*this, From))
4909 return ExprError();
4910
4911 // C++11 [expr.const]p3 with proposed wording fixes:
4912 // A converted constant expression of type T is a core constant expression,
4913 // implicitly converted to a prvalue of type T, where the converted
4914 // expression is a literal constant expression and the implicit conversion
4915 // sequence contains only user-defined conversions, lvalue-to-rvalue
4916 // conversions, integral promotions, and integral conversions other than
4917 // narrowing conversions.
4918 ImplicitConversionSequence ICS =
4919 TryImplicitConversion(From, T,
4920 /*SuppressUserConversions=*/false,
4921 /*AllowExplicit=*/false,
4922 /*InOverloadResolution=*/false,
4923 /*CStyle=*/false,
4924 /*AllowObjcWritebackConversion=*/false);
4925 StandardConversionSequence *SCS = 0;
4926 switch (ICS.getKind()) {
4927 case ImplicitConversionSequence::StandardConversion:
4928 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004929 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004930 diag::err_typecheck_converted_constant_expression_disallowed)
4931 << From->getType() << From->getSourceRange() << T;
4932 SCS = &ICS.Standard;
4933 break;
4934 case ImplicitConversionSequence::UserDefinedConversion:
4935 // We are converting from class type to an integral or enumeration type, so
4936 // the Before sequence must be trivial.
4937 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004938 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004939 diag::err_typecheck_converted_constant_expression_disallowed)
4940 << From->getType() << From->getSourceRange() << T;
4941 SCS = &ICS.UserDefined.After;
4942 break;
4943 case ImplicitConversionSequence::AmbiguousConversion:
4944 case ImplicitConversionSequence::BadConversion:
4945 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004946 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004947 diag::err_typecheck_converted_constant_expression)
4948 << From->getType() << From->getSourceRange() << T;
4949 return ExprError();
4950
4951 case ImplicitConversionSequence::EllipsisConversion:
4952 llvm_unreachable("ellipsis conversion in converted constant expression");
4953 }
4954
4955 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4956 if (Result.isInvalid())
4957 return Result;
4958
4959 // Check for a narrowing implicit conversion.
4960 APValue PreNarrowingValue;
Richard Smithf6028062012-03-23 23:55:39 +00004961 QualType PreNarrowingType;
Richard Smithf6028062012-03-23 23:55:39 +00004962 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4963 PreNarrowingType)) {
Richard Smith8ef7b202012-01-18 23:55:52 +00004964 case NK_Variable_Narrowing:
4965 // Implicit conversion to a narrower type, and the value is not a constant
4966 // expression. We'll diagnose this in a moment.
4967 case NK_Not_Narrowing:
4968 break;
4969
4970 case NK_Constant_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004971 Diag(From->getLocStart(),
4972 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4973 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004974 << CCE << /*Constant*/1
Richard Smithf6028062012-03-23 23:55:39 +00004975 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smith8ef7b202012-01-18 23:55:52 +00004976 break;
4977
4978 case NK_Type_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004979 Diag(From->getLocStart(),
4980 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4981 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004982 << CCE << /*Constant*/0 << From->getType() << T;
4983 break;
4984 }
4985
4986 // Check the expression is a constant expression.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00004987 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith8ef7b202012-01-18 23:55:52 +00004988 Expr::EvalResult Eval;
4989 Eval.Diag = &Notes;
4990
Douglas Gregor484f6fa2013-04-08 23:24:07 +00004991 if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) {
Richard Smith8ef7b202012-01-18 23:55:52 +00004992 // The expression can't be folded, so we can't keep it at this position in
4993 // the AST.
4994 Result = ExprError();
Richard Smithf72fccf2012-01-30 22:27:01 +00004995 } else {
Richard Smith8ef7b202012-01-18 23:55:52 +00004996 Value = Eval.Val.getInt();
Richard Smithf72fccf2012-01-30 22:27:01 +00004997
4998 if (Notes.empty()) {
4999 // It's a constant expression.
5000 return Result;
5001 }
Richard Smith8ef7b202012-01-18 23:55:52 +00005002 }
5003
5004 // It's not a constant expression. Produce an appropriate diagnostic.
5005 if (Notes.size() == 1 &&
5006 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5007 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5008 else {
Daniel Dunbar96a00142012-03-09 18:35:03 +00005009 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smith8ef7b202012-01-18 23:55:52 +00005010 << CCE << From->getSourceRange();
5011 for (unsigned I = 0; I < Notes.size(); ++I)
5012 Diag(Notes[I].first, Notes[I].second);
5013 }
Richard Smithf72fccf2012-01-30 22:27:01 +00005014 return Result;
Richard Smith8ef7b202012-01-18 23:55:52 +00005015}
5016
John McCall0bcc9bc2011-09-09 06:11:02 +00005017/// dropPointerConversions - If the given standard conversion sequence
5018/// involves any pointer conversions, remove them. This may change
5019/// the result type of the conversion sequence.
5020static void dropPointerConversion(StandardConversionSequence &SCS) {
5021 if (SCS.Second == ICK_Pointer_Conversion) {
5022 SCS.Second = ICK_Identity;
5023 SCS.Third = ICK_Identity;
5024 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5025 }
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005026}
John McCall120d63c2010-08-24 20:38:10 +00005027
John McCall0bcc9bc2011-09-09 06:11:02 +00005028/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5029/// convert the expression From to an Objective-C pointer type.
5030static ImplicitConversionSequence
5031TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5032 // Do an implicit conversion to 'id'.
5033 QualType Ty = S.Context.getObjCIdType();
5034 ImplicitConversionSequence ICS
5035 = TryImplicitConversion(S, From, Ty,
5036 // FIXME: Are these flags correct?
5037 /*SuppressUserConversions=*/false,
5038 /*AllowExplicit=*/true,
5039 /*InOverloadResolution=*/false,
5040 /*CStyle=*/false,
5041 /*AllowObjCWritebackConversion=*/false);
5042
5043 // Strip off any final conversions to 'id'.
5044 switch (ICS.getKind()) {
5045 case ImplicitConversionSequence::BadConversion:
5046 case ImplicitConversionSequence::AmbiguousConversion:
5047 case ImplicitConversionSequence::EllipsisConversion:
5048 break;
5049
5050 case ImplicitConversionSequence::UserDefinedConversion:
5051 dropPointerConversion(ICS.UserDefined.After);
5052 break;
5053
5054 case ImplicitConversionSequence::StandardConversion:
5055 dropPointerConversion(ICS.Standard);
5056 break;
5057 }
5058
5059 return ICS;
5060}
5061
5062/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5063/// conversion of the expression From to an Objective-C pointer type.
5064ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00005065 if (checkPlaceholderForOverload(*this, From))
5066 return ExprError();
5067
John McCallc12c5bb2010-05-15 11:32:37 +00005068 QualType Ty = Context.getObjCIdType();
John McCall0bcc9bc2011-09-09 06:11:02 +00005069 ImplicitConversionSequence ICS =
5070 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005071 if (!ICS.isBad())
5072 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley429bb272011-04-08 18:41:53 +00005073 return ExprError();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005074}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005075
Richard Smithf39aec12012-02-04 07:07:42 +00005076/// Determine whether the provided type is an integral type, or an enumeration
5077/// type of a permitted flavor.
Richard Smith097e0a22013-05-21 19:05:48 +00005078bool Sema::ICEConvertDiagnoser::match(QualType T) {
5079 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5080 : T->isIntegralOrUnscopedEnumerationType();
Richard Smithf39aec12012-02-04 07:07:42 +00005081}
5082
Larisse Voufo50b60b32013-06-10 06:50:24 +00005083static ExprResult
5084diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5085 Sema::ContextualImplicitConverter &Converter,
5086 QualType T, UnresolvedSetImpl &ViableConversions) {
5087
5088 if (Converter.Suppress)
5089 return ExprError();
5090
5091 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5092 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5093 CXXConversionDecl *Conv =
5094 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5095 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5096 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5097 }
5098 return SemaRef.Owned(From);
5099}
5100
5101static bool
5102diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5103 Sema::ContextualImplicitConverter &Converter,
5104 QualType T, bool HadMultipleCandidates,
5105 UnresolvedSetImpl &ExplicitConversions) {
5106 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5107 DeclAccessPair Found = ExplicitConversions[0];
5108 CXXConversionDecl *Conversion =
5109 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5110
5111 // The user probably meant to invoke the given explicit
5112 // conversion; use it.
5113 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5114 std::string TypeStr;
5115 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5116
5117 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5118 << FixItHint::CreateInsertion(From->getLocStart(),
5119 "static_cast<" + TypeStr + ">(")
5120 << FixItHint::CreateInsertion(
5121 SemaRef.PP.getLocForEndOfToken(From->getLocEnd()), ")");
5122 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5123
5124 // If we aren't in a SFINAE context, build a call to the
5125 // explicit conversion function.
5126 if (SemaRef.isSFINAEContext())
5127 return true;
5128
5129 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5130 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5131 HadMultipleCandidates);
5132 if (Result.isInvalid())
5133 return true;
5134 // Record usage of conversion in an implicit cast.
5135 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5136 CK_UserDefinedConversion, Result.get(), 0,
5137 Result.get()->getValueKind());
5138 }
5139 return false;
5140}
5141
5142static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5143 Sema::ContextualImplicitConverter &Converter,
5144 QualType T, bool HadMultipleCandidates,
5145 DeclAccessPair &Found) {
5146 CXXConversionDecl *Conversion =
5147 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5148 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5149
5150 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5151 if (!Converter.SuppressConversion) {
5152 if (SemaRef.isSFINAEContext())
5153 return true;
5154
5155 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5156 << From->getSourceRange();
5157 }
5158
5159 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5160 HadMultipleCandidates);
5161 if (Result.isInvalid())
5162 return true;
5163 // Record usage of conversion in an implicit cast.
5164 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5165 CK_UserDefinedConversion, Result.get(), 0,
5166 Result.get()->getValueKind());
5167 return false;
5168}
5169
5170static ExprResult finishContextualImplicitConversion(
5171 Sema &SemaRef, SourceLocation Loc, Expr *From,
5172 Sema::ContextualImplicitConverter &Converter) {
5173 if (!Converter.match(From->getType()) && !Converter.Suppress)
5174 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5175 << From->getSourceRange();
5176
5177 return SemaRef.DefaultLvalueConversion(From);
5178}
5179
5180static void
5181collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5182 UnresolvedSetImpl &ViableConversions,
5183 OverloadCandidateSet &CandidateSet) {
5184 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5185 DeclAccessPair FoundDecl = ViableConversions[I];
5186 NamedDecl *D = FoundDecl.getDecl();
5187 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5188 if (isa<UsingShadowDecl>(D))
5189 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5190
5191 CXXConversionDecl *Conv;
5192 FunctionTemplateDecl *ConvTemplate;
5193 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5194 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5195 else
5196 Conv = cast<CXXConversionDecl>(D);
5197
5198 if (ConvTemplate)
5199 SemaRef.AddTemplateConversionCandidate(
5200 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet);
5201 else
5202 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5203 ToType, CandidateSet);
5204 }
5205}
5206
Richard Smith097e0a22013-05-21 19:05:48 +00005207/// \brief Attempt to convert the given expression to a type which is accepted
5208/// by the given converter.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005209///
Richard Smith097e0a22013-05-21 19:05:48 +00005210/// This routine will attempt to convert an expression of class type to a
5211/// type accepted by the specified converter. In C++11 and before, the class
5212/// must have a single non-explicit conversion function converting to a matching
5213/// type. In C++1y, there can be multiple such conversion functions, but only
5214/// one target type.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005215///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005216/// \param Loc The source location of the construct that requires the
5217/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005218///
James Dennett40ae6662012-06-22 08:52:37 +00005219/// \param From The expression we're converting from.
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005220///
Richard Smith097e0a22013-05-21 19:05:48 +00005221/// \param Converter Used to control and diagnose the conversion process.
Richard Smithf39aec12012-02-04 07:07:42 +00005222///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005223/// \returns The expression, converted to an integral or enumeration type if
5224/// successful.
Richard Smith097e0a22013-05-21 19:05:48 +00005225ExprResult Sema::PerformContextualImplicitConversion(
5226 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005227 // We can't perform any more checking for type-dependent expressions.
5228 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00005229 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005230
Eli Friedmanceccab92012-01-26 00:26:18 +00005231 // Process placeholders immediately.
5232 if (From->hasPlaceholderType()) {
5233 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo50b60b32013-06-10 06:50:24 +00005234 if (result.isInvalid())
5235 return result;
Eli Friedmanceccab92012-01-26 00:26:18 +00005236 From = result.take();
5237 }
5238
Richard Smith097e0a22013-05-21 19:05:48 +00005239 // If the expression already has a matching type, we're golden.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005240 QualType T = From->getType();
Richard Smith097e0a22013-05-21 19:05:48 +00005241 if (Converter.match(T))
Eli Friedmanceccab92012-01-26 00:26:18 +00005242 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005243
5244 // FIXME: Check for missing '()' if T is a function type?
5245
Richard Smith097e0a22013-05-21 19:05:48 +00005246 // We can only perform contextual implicit conversions on objects of class
5247 // type.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005248 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikie4e4d0842012-03-11 07:00:24 +00005249 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smith097e0a22013-05-21 19:05:48 +00005250 if (!Converter.Suppress)
5251 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00005252 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005253 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005254
Douglas Gregorc30614b2010-06-29 23:17:37 +00005255 // We must have a complete class type.
Douglas Gregorf502d8e2012-05-04 16:48:41 +00005256 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smith097e0a22013-05-21 19:05:48 +00005257 ContextualImplicitConverter &Converter;
Douglas Gregorab41fe92012-05-04 22:38:52 +00005258 Expr *From;
Richard Smith097e0a22013-05-21 19:05:48 +00005259
5260 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5261 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5262
Douglas Gregord10099e2012-05-04 16:32:21 +00005263 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Richard Smith097e0a22013-05-21 19:05:48 +00005264 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregord10099e2012-05-04 16:32:21 +00005265 }
Richard Smith097e0a22013-05-21 19:05:48 +00005266 } IncompleteDiagnoser(Converter, From);
Douglas Gregord10099e2012-05-04 16:32:21 +00005267
5268 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCall9ae2f072010-08-23 23:25:46 +00005269 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005270
Douglas Gregorc30614b2010-06-29 23:17:37 +00005271 // Look for a conversion to an integral or enumeration type.
Larisse Voufo50b60b32013-06-10 06:50:24 +00005272 UnresolvedSet<4>
5273 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005274 UnresolvedSet<4> ExplicitConversions;
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00005275 std::pair<CXXRecordDecl::conversion_iterator,
Larisse Voufo50b60b32013-06-10 06:50:24 +00005276 CXXRecordDecl::conversion_iterator> Conversions =
5277 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005278
Larisse Voufo50b60b32013-06-10 06:50:24 +00005279 bool HadMultipleCandidates =
5280 (std::distance(Conversions.first, Conversions.second) > 1);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005281
Larisse Voufo50b60b32013-06-10 06:50:24 +00005282 // To check that there is only one target type, in C++1y:
5283 QualType ToType;
5284 bool HasUniqueTargetType = true;
5285
5286 // Collect explicit or viable (potentially in C++1y) conversions.
5287 for (CXXRecordDecl::conversion_iterator I = Conversions.first,
5288 E = Conversions.second;
5289 I != E; ++I) {
5290 NamedDecl *D = (*I)->getUnderlyingDecl();
5291 CXXConversionDecl *Conversion;
5292 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5293 if (ConvTemplate) {
5294 if (getLangOpts().CPlusPlus1y)
5295 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5296 else
5297 continue; // C++11 does not consider conversion operator templates(?).
5298 } else
5299 Conversion = cast<CXXConversionDecl>(D);
5300
5301 assert((!ConvTemplate || getLangOpts().CPlusPlus1y) &&
5302 "Conversion operator templates are considered potentially "
5303 "viable in C++1y");
5304
5305 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5306 if (Converter.match(CurToType) || ConvTemplate) {
5307
5308 if (Conversion->isExplicit()) {
5309 // FIXME: For C++1y, do we need this restriction?
5310 // cf. diagnoseNoViableConversion()
5311 if (!ConvTemplate)
Douglas Gregorc30614b2010-06-29 23:17:37 +00005312 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo50b60b32013-06-10 06:50:24 +00005313 } else {
5314 if (!ConvTemplate && getLangOpts().CPlusPlus1y) {
5315 if (ToType.isNull())
5316 ToType = CurToType.getUnqualifiedType();
5317 else if (HasUniqueTargetType &&
5318 (CurToType.getUnqualifiedType() != ToType))
5319 HasUniqueTargetType = false;
5320 }
5321 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005322 }
Richard Smithf39aec12012-02-04 07:07:42 +00005323 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005324 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005325
Larisse Voufo50b60b32013-06-10 06:50:24 +00005326 if (getLangOpts().CPlusPlus1y) {
5327 // C++1y [conv]p6:
5328 // ... An expression e of class type E appearing in such a context
5329 // is said to be contextually implicitly converted to a specified
5330 // type T and is well-formed if and only if e can be implicitly
5331 // converted to a type T that is determined as follows: E is searched
Larisse Voufo7acc5a62013-06-10 08:25:58 +00005332 // for conversion functions whose return type is cv T or reference to
5333 // cv T such that T is allowed by the context. There shall be
Larisse Voufo50b60b32013-06-10 06:50:24 +00005334 // exactly one such T.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005335
Larisse Voufo50b60b32013-06-10 06:50:24 +00005336 // If no unique T is found:
5337 if (ToType.isNull()) {
5338 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5339 HadMultipleCandidates,
5340 ExplicitConversions))
Douglas Gregorc30614b2010-06-29 23:17:37 +00005341 return ExprError();
Larisse Voufo50b60b32013-06-10 06:50:24 +00005342 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005343 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005344
Larisse Voufo50b60b32013-06-10 06:50:24 +00005345 // If more than one unique Ts are found:
5346 if (!HasUniqueTargetType)
5347 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5348 ViableConversions);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005349
Larisse Voufo50b60b32013-06-10 06:50:24 +00005350 // If one unique T is found:
5351 // First, build a candidate set from the previously recorded
5352 // potentially viable conversions.
5353 OverloadCandidateSet CandidateSet(Loc);
5354 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5355 CandidateSet);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005356
Larisse Voufo50b60b32013-06-10 06:50:24 +00005357 // Then, perform overload resolution over the candidate set.
5358 OverloadCandidateSet::iterator Best;
5359 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5360 case OR_Success: {
5361 // Apply this conversion.
5362 DeclAccessPair Found =
5363 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5364 if (recordConversion(*this, Loc, From, Converter, T,
5365 HadMultipleCandidates, Found))
5366 return ExprError();
5367 break;
5368 }
5369 case OR_Ambiguous:
5370 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5371 ViableConversions);
5372 case OR_No_Viable_Function:
5373 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5374 HadMultipleCandidates,
5375 ExplicitConversions))
5376 return ExprError();
5377 // fall through 'OR_Deleted' case.
5378 case OR_Deleted:
5379 // We'll complain below about a non-integral condition type.
5380 break;
5381 }
5382 } else {
5383 switch (ViableConversions.size()) {
5384 case 0: {
5385 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5386 HadMultipleCandidates,
5387 ExplicitConversions))
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005388 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005389
Larisse Voufo50b60b32013-06-10 06:50:24 +00005390 // We'll complain below about a non-integral condition type.
5391 break;
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005392 }
Larisse Voufo50b60b32013-06-10 06:50:24 +00005393 case 1: {
5394 // Apply this conversion.
5395 DeclAccessPair Found = ViableConversions[0];
5396 if (recordConversion(*this, Loc, From, Converter, T,
5397 HadMultipleCandidates, Found))
5398 return ExprError();
5399 break;
5400 }
5401 default:
5402 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5403 ViableConversions);
5404 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005405 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005406
Larisse Voufo50b60b32013-06-10 06:50:24 +00005407 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005408}
5409
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005410/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00005411/// candidate functions, using the given function call arguments. If
5412/// @p SuppressUserConversions, then don't allow user-defined
5413/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005414///
James Dennett699c9042012-06-15 07:13:21 +00005415/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005416/// based on an incomplete set of function arguments. This feature is used by
5417/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00005418void
5419Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00005420 DeclAccessPair FoundDecl,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005421 ArrayRef<Expr *> Args,
Douglas Gregor225c41e2008-11-03 19:09:14 +00005422 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00005423 bool SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00005424 bool PartialOverloading,
5425 bool AllowExplicit) {
Mike Stump1eb44332009-09-09 15:08:12 +00005426 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005427 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005428 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00005429 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi00995302011-01-27 07:09:49 +00005430 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00005431
Douglas Gregor88a35142008-12-22 05:46:06 +00005432 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005433 if (!isa<CXXConstructorDecl>(Method)) {
5434 // If we get here, it's because we're calling a member function
5435 // that is named without a member access expression (e.g.,
5436 // "this->f") that was either written explicitly or created
5437 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00005438 // function, e.g., X::f(). We use an empty type for the implied
5439 // object argument (C++ [over.call.func]p3), and the acting context
5440 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00005441 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005442 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005443 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005444 return;
5445 }
5446 // We treat a constructor like a non-member function, since its object
5447 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00005448 }
5449
Douglas Gregorfd476482009-11-13 23:59:09 +00005450 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00005451 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00005452
Douglas Gregor7edfb692009-11-23 12:27:39 +00005453 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005454 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005455
Douglas Gregor66724ea2009-11-14 01:20:54 +00005456 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5457 // C++ [class.copy]p3:
5458 // A member function template is never instantiated to perform the copy
5459 // of a class object to an object of its class type.
5460 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charles13a140c2012-02-25 11:00:22 +00005461 if (Args.size() == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00005462 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00005463 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5464 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00005465 return;
5466 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005467
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005468 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005469 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCall9aa472c2010-03-19 07:35:19 +00005470 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005471 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00005472 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005473 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005474 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005475 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005476
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005477 unsigned NumArgsInProto = Proto->getNumArgs();
5478
5479 // (C++ 13.3.2p2): A candidate function having fewer than m
5480 // parameters is viable only if it has an ellipsis in its parameter
5481 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005482 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor5bd1a112009-09-23 14:56:09 +00005483 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005484 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005485 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005486 return;
5487 }
5488
5489 // (C++ 13.3.2p2): A candidate function having more than m parameters
5490 // is viable only if the (m+1)st parameter has a default argument
5491 // (8.3.6). For the purposes of overload resolution, the
5492 // parameter list is truncated on the right, so that there are
5493 // exactly m parameters.
5494 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005495 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005496 // Not enough arguments.
5497 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005498 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005499 return;
5500 }
5501
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005502 // (CUDA B.1): Check for invalid calls between targets.
David Blaikie4e4d0842012-03-11 07:00:24 +00005503 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005504 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5505 if (CheckCUDATarget(Caller, Function)) {
5506 Candidate.Viable = false;
5507 Candidate.FailureKind = ovl_fail_bad_target;
5508 return;
5509 }
5510
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005511 // Determine the implicit conversion sequences for each of the
5512 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005513 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005514 if (ArgIdx < NumArgsInProto) {
5515 // (C++ 13.3.2p3): for F to be a viable function, there shall
5516 // exist for each argument an implicit conversion sequence
5517 // (13.3.3.1) that converts that argument to the corresponding
5518 // parameter of F.
5519 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005520 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005521 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005522 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005523 /*InOverloadResolution=*/true,
5524 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005525 getLangOpts().ObjCAutoRefCount,
Douglas Gregored878af2012-02-24 23:56:31 +00005526 AllowExplicit);
John McCall1d318332010-01-12 00:44:57 +00005527 if (Candidate.Conversions[ArgIdx].isBad()) {
5528 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005529 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00005530 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00005531 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005532 } else {
5533 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5534 // argument for which there is no corresponding parameter is
5535 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005536 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005537 }
5538 }
5539}
5540
Douglas Gregor063daf62009-03-13 18:40:31 +00005541/// \brief Add all of the function declarations in the given function set to
5542/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00005543void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005544 ArrayRef<Expr *> Args,
Douglas Gregor063daf62009-03-13 18:40:31 +00005545 OverloadCandidateSet& CandidateSet,
Richard Smith36f5cfe2012-03-09 08:00:36 +00005546 bool SuppressUserConversions,
5547 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall6e266892010-01-26 03:27:55 +00005548 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00005549 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5550 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005551 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005552 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005553 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005554 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005555 Args.slice(1), CandidateSet,
5556 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005557 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00005558 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00005559 SuppressUserConversions);
5560 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005561 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00005562 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5563 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005564 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005565 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005566 ExplicitTemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005567 Args[0]->getType(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005568 Args[0]->Classify(Context), Args.slice(1),
5569 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005570 else
John McCall9aa472c2010-03-19 07:35:19 +00005571 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005572 ExplicitTemplateArgs, Args,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005573 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005574 }
Douglas Gregor364e0212009-06-27 21:05:07 +00005575 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005576}
5577
John McCall314be4e2009-11-17 07:50:12 +00005578/// AddMethodCandidate - Adds a named decl (which is some kind of
5579/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00005580void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005581 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005582 Expr::Classification ObjectClassification,
Rafael Espindola548107e2013-04-29 19:29:25 +00005583 ArrayRef<Expr *> Args,
John McCall314be4e2009-11-17 07:50:12 +00005584 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005585 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00005586 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00005587 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00005588
5589 if (isa<UsingShadowDecl>(Decl))
5590 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005591
John McCall314be4e2009-11-17 07:50:12 +00005592 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5593 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5594 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00005595 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5596 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005597 ObjectType, ObjectClassification,
Rafael Espindola548107e2013-04-29 19:29:25 +00005598 Args, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005599 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005600 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005601 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005602 ObjectType, ObjectClassification,
Rafael Espindola548107e2013-04-29 19:29:25 +00005603 Args,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005604 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005605 }
5606}
5607
Douglas Gregor96176b32008-11-18 23:14:02 +00005608/// AddMethodCandidate - Adds the given C++ member function to the set
5609/// of candidate functions, using the given function call arguments
5610/// and the object argument (@c Object). For example, in a call
5611/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5612/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5613/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00005614/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00005615void
John McCall9aa472c2010-03-19 07:35:19 +00005616Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00005617 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005618 Expr::Classification ObjectClassification,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005619 ArrayRef<Expr *> Args,
Douglas Gregor96176b32008-11-18 23:14:02 +00005620 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005621 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00005622 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005623 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00005624 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005625 assert(!isa<CXXConstructorDecl>(Method) &&
5626 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00005627
Douglas Gregor3f396022009-09-28 04:47:19 +00005628 if (!CandidateSet.isNewCandidate(Method))
5629 return;
5630
Douglas Gregor7edfb692009-11-23 12:27:39 +00005631 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005632 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005633
Douglas Gregor96176b32008-11-18 23:14:02 +00005634 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005635 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005636 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00005637 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005638 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005639 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005640 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor96176b32008-11-18 23:14:02 +00005641
5642 unsigned NumArgsInProto = Proto->getNumArgs();
5643
5644 // (C++ 13.3.2p2): A candidate function having fewer than m
5645 // parameters is viable only if it has an ellipsis in its parameter
5646 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005647 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005648 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005649 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005650 return;
5651 }
5652
5653 // (C++ 13.3.2p2): A candidate function having more than m parameters
5654 // is viable only if the (m+1)st parameter has a default argument
5655 // (8.3.6). For the purposes of overload resolution, the
5656 // parameter list is truncated on the right, so that there are
5657 // exactly m parameters.
5658 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005659 if (Args.size() < MinRequiredArgs) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005660 // Not enough arguments.
5661 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005662 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005663 return;
5664 }
5665
5666 Candidate.Viable = true;
Douglas Gregor96176b32008-11-18 23:14:02 +00005667
John McCall701c89e2009-12-03 04:06:58 +00005668 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00005669 // The implicit object argument is ignored.
5670 Candidate.IgnoreObjectArgument = true;
5671 else {
5672 // Determine the implicit conversion sequence for the object
5673 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00005674 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005675 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5676 Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005677 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00005678 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005679 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00005680 return;
5681 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005682 }
5683
5684 // Determine the implicit conversion sequences for each of the
5685 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005686 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005687 if (ArgIdx < NumArgsInProto) {
5688 // (C++ 13.3.2p3): for F to be a viable function, there shall
5689 // exist for each argument an implicit conversion sequence
5690 // (13.3.3.1) that converts that argument to the corresponding
5691 // parameter of F.
5692 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005693 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005694 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005695 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005696 /*InOverloadResolution=*/true,
5697 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005698 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005699 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005700 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005701 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00005702 break;
5703 }
5704 } else {
5705 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5706 // argument for which there is no corresponding parameter is
5707 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005708 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00005709 }
5710 }
5711}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005712
Douglas Gregor6b906862009-08-21 00:16:32 +00005713/// \brief Add a C++ member function template as a candidate to the candidate
5714/// set, using template argument deduction to produce an appropriate member
5715/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005716void
Douglas Gregor6b906862009-08-21 00:16:32 +00005717Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00005718 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005719 CXXRecordDecl *ActingContext,
Douglas Gregor67714232011-03-03 02:41:12 +00005720 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00005721 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005722 Expr::Classification ObjectClassification,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005723 ArrayRef<Expr *> Args,
Douglas Gregor6b906862009-08-21 00:16:32 +00005724 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005725 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005726 if (!CandidateSet.isNewCandidate(MethodTmpl))
5727 return;
5728
Douglas Gregor6b906862009-08-21 00:16:32 +00005729 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005730 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00005731 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005732 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00005733 // candidate functions in the usual way.113) A given name can refer to one
5734 // or more function templates and also to a set of overloaded non-template
5735 // functions. In such a case, the candidate functions generated from each
5736 // function template are combined with the set of non-template candidate
5737 // functions.
Craig Topper93e45992012-09-19 02:26:47 +00005738 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00005739 FunctionDecl *Specialization = 0;
5740 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005741 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5742 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005743 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005744 Candidate.FoundDecl = FoundDecl;
5745 Candidate.Function = MethodTmpl->getTemplatedDecl();
5746 Candidate.Viable = false;
5747 Candidate.FailureKind = ovl_fail_bad_deduction;
5748 Candidate.IsSurrogate = false;
5749 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005750 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005751 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005752 Info);
5753 return;
5754 }
Mike Stump1eb44332009-09-09 15:08:12 +00005755
Douglas Gregor6b906862009-08-21 00:16:32 +00005756 // Add the function template specialization produced by template argument
5757 // deduction as a candidate.
5758 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00005759 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00005760 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00005761 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005762 ActingContext, ObjectType, ObjectClassification, Args,
5763 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00005764}
5765
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005766/// \brief Add a C++ function template specialization as a candidate
5767/// in the candidate set, using template argument deduction to produce
5768/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005769void
Douglas Gregore53060f2009-06-25 22:08:12 +00005770Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005771 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00005772 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005773 ArrayRef<Expr *> Args,
Douglas Gregore53060f2009-06-25 22:08:12 +00005774 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005775 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005776 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5777 return;
5778
Douglas Gregore53060f2009-06-25 22:08:12 +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 Gregore53060f2009-06-25 22:08:12 +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 Gregore53060f2009-06-25 22:08:12 +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 Gregore53060f2009-06-25 22:08:12 +00005789 FunctionDecl *Specialization = 0;
5790 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005791 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5792 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005793 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCall9aa472c2010-03-19 07:35:19 +00005794 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00005795 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5796 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005797 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00005798 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);
Douglas Gregore53060f2009-06-25 22:08:12 +00005803 return;
5804 }
Mike Stump1eb44332009-09-09 15:08:12 +00005805
Douglas Gregore53060f2009-06-25 22:08:12 +00005806 // Add the function template specialization produced by template argument
5807 // deduction as a candidate.
5808 assert(Specialization && "Missing function template specialization?");
Ahmed Charles13a140c2012-02-25 11:00:22 +00005809 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005810 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00005811}
Mike Stump1eb44332009-09-09 15:08:12 +00005812
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005813/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00005814/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005815/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00005816/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005817/// (which may or may not be the same type as the type that the
5818/// conversion function produces).
5819void
5820Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005821 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005822 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005823 Expr *From, QualType ToType,
5824 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005825 assert(!Conversion->getDescribedFunctionTemplate() &&
5826 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005827 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00005828 if (!CandidateSet.isNewCandidate(Conversion))
5829 return;
5830
Richard Smith60e141e2013-05-04 07:00:32 +00005831 // If the conversion function has an undeduced return type, trigger its
5832 // deduction now.
5833 if (getLangOpts().CPlusPlus1y && ConvType->isUndeducedType()) {
5834 if (DeduceReturnType(Conversion, From->getExprLoc()))
5835 return;
5836 ConvType = Conversion->getConversionType().getNonReferenceType();
5837 }
5838
Douglas Gregor7edfb692009-11-23 12:27:39 +00005839 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005840 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005841
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005842 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005843 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCall9aa472c2010-03-19 07:35:19 +00005844 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005845 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005846 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005847 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005848 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005849 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00005850 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005851 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005852 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005853
Douglas Gregorbca39322010-08-19 15:37:02 +00005854 // C++ [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005855 // For conversion functions, the function is considered to be a member of
5856 // the class of the implicit implied object argument for the purpose of
Douglas Gregorbca39322010-08-19 15:37:02 +00005857 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005858 //
5859 // Determine the implicit conversion sequence for the implicit
5860 // object parameter.
5861 QualType ImplicitParamType = From->getType();
5862 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5863 ImplicitParamType = FromPtrType->getPointeeType();
5864 CXXRecordDecl *ConversionContext
5865 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005866
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005867 Candidate.Conversions[0]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005868 = TryObjectArgumentInitialization(*this, From->getType(),
5869 From->Classify(Context),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005870 Conversion, ConversionContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005871
John McCall1d318332010-01-12 00:44:57 +00005872 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005873 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005874 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005875 return;
5876 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005877
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005878 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005879 // derived to base as such conversions are given Conversion Rank. They only
5880 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5881 QualType FromCanon
5882 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5883 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5884 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5885 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005886 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005887 return;
5888 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005889
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005890 // To determine what the conversion from the result of calling the
5891 // conversion function to the type we're eventually trying to
5892 // convert to (ToType), we need to synthesize a call to the
5893 // conversion function and attempt copy initialization from it. This
5894 // makes sure that we get the right semantics with respect to
5895 // lvalues/rvalues and the type. Fortunately, we can allocate this
5896 // call on the stack and we don't need its arguments to be
5897 // well-formed.
John McCallf4b88a42012-03-10 09:33:50 +00005898 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005899 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00005900 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5901 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00005902 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00005903 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00005904
Richard Smith87c1f1f2011-07-13 22:53:21 +00005905 QualType ConversionType = Conversion->getConversionType();
5906 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor7d14d382010-11-13 19:36:57 +00005907 Candidate.Viable = false;
5908 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5909 return;
5910 }
5911
Richard Smith87c1f1f2011-07-13 22:53:21 +00005912 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCallf89e55a2010-11-18 06:31:45 +00005913
Mike Stump1eb44332009-09-09 15:08:12 +00005914 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00005915 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5916 // allocator).
Richard Smith87c1f1f2011-07-13 22:53:21 +00005917 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00005918 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00005919 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00005920 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00005921 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005922 /*SuppressUserConversions=*/true,
John McCallf85e1932011-06-15 23:02:42 +00005923 /*InOverloadResolution=*/false,
5924 /*AllowObjCWritebackConversion=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00005925
John McCall1d318332010-01-12 00:44:57 +00005926 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005927 case ImplicitConversionSequence::StandardConversion:
5928 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005929
Douglas Gregorc520c842010-04-12 23:42:09 +00005930 // C++ [over.ics.user]p3:
5931 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005932 // conversion function template, the second standard conversion sequence
Douglas Gregorc520c842010-04-12 23:42:09 +00005933 // shall have exact match rank.
5934 if (Conversion->getPrimaryTemplate() &&
5935 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5936 Candidate.Viable = false;
5937 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5938 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005939
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005940 // C++0x [dcl.init.ref]p5:
5941 // In the second case, if the reference is an rvalue reference and
5942 // the second standard conversion sequence of the user-defined
5943 // conversion sequence includes an lvalue-to-rvalue conversion, the
5944 // program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005945 if (ToType->isRValueReferenceType() &&
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005946 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5947 Candidate.Viable = false;
5948 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5949 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005950 break;
5951
5952 case ImplicitConversionSequence::BadConversion:
5953 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005954 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005955 break;
5956
5957 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00005958 llvm_unreachable(
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005959 "Can only end up with a standard conversion sequence or failure");
5960 }
5961}
5962
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005963/// \brief Adds a conversion function template specialization
5964/// candidate to the overload set, using template argument deduction
5965/// to deduce the template arguments of the conversion function
5966/// template from the type that we are converting to (C++
5967/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00005968void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005969Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005970 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005971 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005972 Expr *From, QualType ToType,
5973 OverloadCandidateSet &CandidateSet) {
5974 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5975 "Only conversion function templates permitted here");
5976
Douglas Gregor3f396022009-09-28 04:47:19 +00005977 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5978 return;
5979
Craig Topper93e45992012-09-19 02:26:47 +00005980 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005981 CXXConversionDecl *Specialization = 0;
5982 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00005983 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005984 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005985 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005986 Candidate.FoundDecl = FoundDecl;
5987 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5988 Candidate.Viable = false;
5989 Candidate.FailureKind = ovl_fail_bad_deduction;
5990 Candidate.IsSurrogate = false;
5991 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005992 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005993 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005994 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005995 return;
5996 }
Mike Stump1eb44332009-09-09 15:08:12 +00005997
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005998 // Add the conversion function template specialization produced by
5999 // template argument deduction as a candidate.
6000 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00006001 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00006002 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006003}
6004
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006005/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6006/// converts the given @c Object to a function pointer via the
6007/// conversion function @c Conversion, and then attempts to call it
6008/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6009/// the type of function that we'll eventually be calling.
6010void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00006011 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00006012 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00006013 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006014 Expr *Object,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006015 ArrayRef<Expr *> Args,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006016 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00006017 if (!CandidateSet.isNewCandidate(Conversion))
6018 return;
6019
Douglas Gregor7edfb692009-11-23 12:27:39 +00006020 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00006021 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00006022
Ahmed Charles13a140c2012-02-25 11:00:22 +00006023 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00006024 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006025 Candidate.Function = 0;
6026 Candidate.Surrogate = Conversion;
6027 Candidate.Viable = true;
6028 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00006029 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00006030 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006031
6032 // Determine the implicit conversion sequence for the implicit
6033 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00006034 ImplicitConversionSequence ObjectInit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006035 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006036 Object->Classify(Context),
6037 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00006038 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006039 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006040 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00006041 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006042 return;
6043 }
6044
6045 // The first conversion is actually a user-defined conversion whose
6046 // first conversion is ObjectInit's standard conversion (which is
6047 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00006048 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006049 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00006050 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00006051 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006052 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00006053 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00006054 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006055 = Candidate.Conversions[0].UserDefined.Before;
6056 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6057
Mike Stump1eb44332009-09-09 15:08:12 +00006058 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006059 unsigned NumArgsInProto = Proto->getNumArgs();
6060
6061 // (C++ 13.3.2p2): A candidate function having fewer than m
6062 // parameters is viable only if it has an ellipsis in its parameter
6063 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00006064 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006065 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006066 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006067 return;
6068 }
6069
6070 // Function types don't have any default arguments, so just check if
6071 // we have enough arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00006072 if (Args.size() < NumArgsInProto) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006073 // Not enough arguments.
6074 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006075 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006076 return;
6077 }
6078
6079 // Determine the implicit conversion sequences for each of the
6080 // arguments.
Richard Smith958ba642013-05-05 15:51:06 +00006081 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006082 if (ArgIdx < NumArgsInProto) {
6083 // (C++ 13.3.2p3): for F to be a viable function, there shall
6084 // exist for each argument an implicit conversion sequence
6085 // (13.3.3.1) that converts that argument to the corresponding
6086 // parameter of F.
6087 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00006088 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006089 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00006090 /*SuppressUserConversions=*/false,
John McCallf85e1932011-06-15 23:02:42 +00006091 /*InOverloadResolution=*/false,
6092 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00006093 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00006094 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006095 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006096 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006097 break;
6098 }
6099 } else {
6100 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6101 // argument for which there is no corresponding parameter is
6102 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00006103 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006104 }
6105 }
6106}
6107
Douglas Gregor063daf62009-03-13 18:40:31 +00006108/// \brief Add overload candidates for overloaded operators that are
6109/// member functions.
6110///
6111/// Add the overloaded operator candidates that are member functions
6112/// for the operator Op that was used in an operator expression such
6113/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6114/// CandidateSet will store the added overload candidates. (C++
6115/// [over.match.oper]).
6116void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6117 SourceLocation OpLoc,
Richard Smith958ba642013-05-05 15:51:06 +00006118 ArrayRef<Expr *> Args,
Douglas Gregor063daf62009-03-13 18:40:31 +00006119 OverloadCandidateSet& CandidateSet,
6120 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00006121 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6122
6123 // C++ [over.match.oper]p3:
6124 // For a unary operator @ with an operand of a type whose
6125 // cv-unqualified version is T1, and for a binary operator @ with
6126 // a left operand of a type whose cv-unqualified version is T1 and
6127 // a right operand of a type whose cv-unqualified version is T2,
6128 // three sets of candidate functions, designated member
6129 // candidates, non-member candidates and built-in candidates, are
6130 // constructed as follows:
6131 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00006132
Richard Smithe410be92013-04-20 12:41:22 +00006133 // -- If T1 is a complete class type or a class currently being
6134 // defined, the set of member candidates is the result of the
6135 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6136 // the set of member candidates is empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00006137 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smithe410be92013-04-20 12:41:22 +00006138 // Complete the type if it can be completed.
6139 RequireCompleteType(OpLoc, T1, 0);
6140 // If the type is neither complete nor being defined, bail out now.
6141 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor8a5ae242009-08-27 23:35:55 +00006142 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006143
John McCalla24dc2e2009-11-17 02:14:36 +00006144 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6145 LookupQualifiedName(Operators, T1Rec->getDecl());
6146 Operators.suppressDiagnostics();
6147
Mike Stump1eb44332009-09-09 15:08:12 +00006148 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00006149 OperEnd = Operators.end();
6150 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00006151 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00006152 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola548107e2013-04-29 19:29:25 +00006153 Args[0]->Classify(Context),
Richard Smith958ba642013-05-05 15:51:06 +00006154 Args.slice(1),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006155 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00006156 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00006157 }
Douglas Gregor96176b32008-11-18 23:14:02 +00006158}
6159
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006160/// AddBuiltinCandidate - Add a candidate for a built-in
6161/// operator. ResultTy and ParamTys are the result and parameter types
6162/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006163/// arguments being passed to the candidate. IsAssignmentOperator
6164/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006165/// operator. NumContextualBoolArguments is the number of arguments
6166/// (at the beginning of the argument list) that will be contextually
6167/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00006168void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smith958ba642013-05-05 15:51:06 +00006169 ArrayRef<Expr *> Args,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006170 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006171 bool IsAssignmentOperator,
6172 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00006173 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00006174 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00006175
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006176 // Add this candidate
Richard Smith958ba642013-05-05 15:51:06 +00006177 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCall9aa472c2010-03-19 07:35:19 +00006178 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006179 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00006180 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00006181 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006182 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smith958ba642013-05-05 15:51:06 +00006183 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006184 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6185
6186 // Determine the implicit conversion sequences for each of the
6187 // arguments.
6188 Candidate.Viable = true;
Richard Smith958ba642013-05-05 15:51:06 +00006189 Candidate.ExplicitCallArguments = Args.size();
6190 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006191 // C++ [over.match.oper]p4:
6192 // For the built-in assignment operators, conversions of the
6193 // left operand are restricted as follows:
6194 // -- no temporaries are introduced to hold the left operand, and
6195 // -- no user-defined conversions are applied to the left
6196 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00006197 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006198 //
6199 // We block these conversions by turning off user-defined
6200 // conversions, since that is the only way that initialization of
6201 // a reference to a non-class type can occur from something that
6202 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006203 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00006204 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006205 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00006206 Candidate.Conversions[ArgIdx]
6207 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006208 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00006209 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006210 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00006211 ArgIdx == 0 && IsAssignmentOperator,
John McCallf85e1932011-06-15 23:02:42 +00006212 /*InOverloadResolution=*/false,
6213 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00006214 getLangOpts().ObjCAutoRefCount);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006215 }
John McCall1d318332010-01-12 00:44:57 +00006216 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006217 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006218 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00006219 break;
6220 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006221 }
6222}
6223
Craig Topperfe09f3f2013-07-01 06:29:40 +00006224namespace {
6225
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006226/// BuiltinCandidateTypeSet - A set of types that will be used for the
6227/// candidate operator functions for built-in operators (C++
6228/// [over.built]). The types are separated into pointer types and
6229/// enumeration types.
6230class BuiltinCandidateTypeSet {
6231 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006232 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006233
6234 /// PointerTypes - The set of pointer types that will be used in the
6235 /// built-in candidates.
6236 TypeSet PointerTypes;
6237
Sebastian Redl78eb8742009-04-19 21:53:20 +00006238 /// MemberPointerTypes - The set of member pointer types that will be
6239 /// used in the built-in candidates.
6240 TypeSet MemberPointerTypes;
6241
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006242 /// EnumerationTypes - The set of enumeration types that will be
6243 /// used in the built-in candidates.
6244 TypeSet EnumerationTypes;
6245
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006246 /// \brief The set of vector types that will be used in the built-in
Douglas Gregor26bcf672010-05-19 03:21:00 +00006247 /// candidates.
6248 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00006249
6250 /// \brief A flag indicating non-record types are viable candidates
6251 bool HasNonRecordTypes;
6252
6253 /// \brief A flag indicating whether either arithmetic or enumeration types
6254 /// were present in the candidate set.
6255 bool HasArithmeticOrEnumeralTypes;
6256
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006257 /// \brief A flag indicating whether the nullptr type was present in the
6258 /// candidate set.
6259 bool HasNullPtrType;
6260
Douglas Gregor5842ba92009-08-24 15:23:48 +00006261 /// Sema - The semantic analysis instance where we are building the
6262 /// candidate type set.
6263 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00006264
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006265 /// Context - The AST context in which we will build the type sets.
6266 ASTContext &Context;
6267
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006268 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6269 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00006270 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006271
6272public:
6273 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006274 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006275
Mike Stump1eb44332009-09-09 15:08:12 +00006276 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00006277 : HasNonRecordTypes(false),
6278 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006279 HasNullPtrType(false),
Chandler Carruth6a577462010-12-13 01:44:01 +00006280 SemaRef(SemaRef),
6281 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006282
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006283 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006284 SourceLocation Loc,
6285 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006286 bool AllowExplicitConversions,
6287 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006288
6289 /// pointer_begin - First pointer type found;
6290 iterator pointer_begin() { return PointerTypes.begin(); }
6291
Sebastian Redl78eb8742009-04-19 21:53:20 +00006292 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006293 iterator pointer_end() { return PointerTypes.end(); }
6294
Sebastian Redl78eb8742009-04-19 21:53:20 +00006295 /// member_pointer_begin - First member pointer type found;
6296 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6297
6298 /// member_pointer_end - Past the last member pointer type found;
6299 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6300
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006301 /// enumeration_begin - First enumeration type found;
6302 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6303
Sebastian Redl78eb8742009-04-19 21:53:20 +00006304 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006305 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006306
Douglas Gregor26bcf672010-05-19 03:21:00 +00006307 iterator vector_begin() { return VectorTypes.begin(); }
6308 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00006309
6310 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6311 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006312 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006313};
6314
Craig Topperfe09f3f2013-07-01 06:29:40 +00006315} // end anonymous namespace
6316
Sebastian Redl78eb8742009-04-19 21:53:20 +00006317/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006318/// the set of pointer types along with any more-qualified variants of
6319/// that type. For example, if @p Ty is "int const *", this routine
6320/// will add "int const *", "int const volatile *", "int const
6321/// restrict *", and "int const volatile restrict *" to the set of
6322/// pointer types. Returns true if the add of @p Ty itself succeeded,
6323/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006324///
6325/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006326bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00006327BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6328 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00006329
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006330 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006331 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006332 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006333
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006334 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00006335 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006336 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006337 if (!PointerTy) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006338 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6339 PointeeTy = PTy->getPointeeType();
6340 buildObjCPtr = true;
6341 } else {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006342 PointeeTy = PointerTy->getPointeeType();
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006343 }
6344
Sebastian Redla9efada2009-11-18 20:39:26 +00006345 // Don't add qualified variants of arrays. For one, they're not allowed
6346 // (the qualifier would sink to the element type), and for another, the
6347 // only overload situation where it matters is subscript or pointer +- int,
6348 // and those shouldn't have qualifier variants anyway.
6349 if (PointeeTy->isArrayType())
6350 return true;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006351
John McCall0953e762009-09-24 19:53:00 +00006352 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006353 bool hasVolatile = VisibleQuals.hasVolatile();
6354 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006355
John McCall0953e762009-09-24 19:53:00 +00006356 // Iterate through all strict supersets of BaseCVR.
6357 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6358 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006359 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006360 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006361
6362 // Skip over restrict if no restrict found anywhere in the types, or if
6363 // the type cannot be restrict-qualified.
6364 if ((CVR & Qualifiers::Restrict) &&
6365 (!hasRestrict ||
6366 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6367 continue;
6368
6369 // Build qualified pointee type.
John McCall0953e762009-09-24 19:53:00 +00006370 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006371
6372 // Build qualified pointer type.
6373 QualType QPointerTy;
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006374 if (!buildObjCPtr)
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006375 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006376 else
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006377 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6378
6379 // Insert qualified pointer type.
6380 PointerTypes.insert(QPointerTy);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006381 }
6382
6383 return true;
6384}
6385
Sebastian Redl78eb8742009-04-19 21:53:20 +00006386/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6387/// to the set of pointer types along with any more-qualified variants of
6388/// that type. For example, if @p Ty is "int const *", this routine
6389/// will add "int const *", "int const volatile *", "int const
6390/// restrict *", and "int const volatile restrict *" to the set of
6391/// pointer types. Returns true if the add of @p Ty itself succeeded,
6392/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006393///
6394/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006395bool
6396BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6397 QualType Ty) {
6398 // Insert this type.
6399 if (!MemberPointerTypes.insert(Ty))
6400 return false;
6401
John McCall0953e762009-09-24 19:53:00 +00006402 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6403 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00006404
John McCall0953e762009-09-24 19:53:00 +00006405 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00006406 // Don't add qualified variants of arrays. For one, they're not allowed
6407 // (the qualifier would sink to the element type), and for another, the
6408 // only overload situation where it matters is subscript or pointer +- int,
6409 // and those shouldn't have qualifier variants anyway.
6410 if (PointeeTy->isArrayType())
6411 return true;
John McCall0953e762009-09-24 19:53:00 +00006412 const Type *ClassTy = PointerTy->getClass();
6413
6414 // Iterate through all strict supersets of the pointee type's CVR
6415 // qualifiers.
6416 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6417 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6418 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006419
John McCall0953e762009-09-24 19:53:00 +00006420 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006421 MemberPointerTypes.insert(
6422 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00006423 }
6424
6425 return true;
6426}
6427
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006428/// AddTypesConvertedFrom - Add each of the types to which the type @p
6429/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00006430/// primarily interested in pointer types and enumeration types. We also
6431/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006432/// AllowUserConversions is true if we should look at the conversion
6433/// functions of a class type, and AllowExplicitConversions if we
6434/// should also include the explicit conversion functions of a class
6435/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00006436void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006437BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006438 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006439 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006440 bool AllowExplicitConversions,
6441 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006442 // Only deal with canonical types.
6443 Ty = Context.getCanonicalType(Ty);
6444
6445 // Look through reference types; they aren't part of the type of an
6446 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00006447 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006448 Ty = RefTy->getPointeeType();
6449
John McCall3b657512011-01-19 10:06:00 +00006450 // If we're dealing with an array type, decay to the pointer.
6451 if (Ty->isArrayType())
6452 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6453
6454 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006455 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006456
Chandler Carruth6a577462010-12-13 01:44:01 +00006457 // Flag if we ever add a non-record type.
6458 const RecordType *TyRec = Ty->getAs<RecordType>();
6459 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6460
Chandler Carruth6a577462010-12-13 01:44:01 +00006461 // Flag if we encounter an arithmetic type.
6462 HasArithmeticOrEnumeralTypes =
6463 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6464
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006465 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6466 PointerTypes.insert(Ty);
6467 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006468 // Insert our type, and its more-qualified variants, into the set
6469 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006470 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006471 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00006472 } else if (Ty->isMemberPointerType()) {
6473 // Member pointers are far easier, since the pointee can't be converted.
6474 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6475 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006476 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006477 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00006478 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006479 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006480 // We treat vector types as arithmetic types in many contexts as an
6481 // extension.
6482 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00006483 VectorTypes.insert(Ty);
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006484 } else if (Ty->isNullPtrType()) {
6485 HasNullPtrType = true;
Chandler Carruth6a577462010-12-13 01:44:01 +00006486 } else if (AllowUserConversions && TyRec) {
6487 // No conversion functions in incomplete types.
6488 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6489 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006490
Chandler Carruth6a577462010-12-13 01:44:01 +00006491 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006492 std::pair<CXXRecordDecl::conversion_iterator,
6493 CXXRecordDecl::conversion_iterator>
6494 Conversions = ClassDecl->getVisibleConversionFunctions();
6495 for (CXXRecordDecl::conversion_iterator
6496 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006497 NamedDecl *D = I.getDecl();
6498 if (isa<UsingShadowDecl>(D))
6499 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006500
Chandler Carruth6a577462010-12-13 01:44:01 +00006501 // Skip conversion function templates; they don't tell us anything
6502 // about which builtin types we can convert to.
6503 if (isa<FunctionTemplateDecl>(D))
6504 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006505
Chandler Carruth6a577462010-12-13 01:44:01 +00006506 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6507 if (AllowExplicitConversions || !Conv->isExplicit()) {
6508 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6509 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006510 }
6511 }
6512 }
6513}
6514
Douglas Gregor19b7b152009-08-24 13:43:27 +00006515/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6516/// the volatile- and non-volatile-qualified assignment operators for the
6517/// given type to the candidate set.
6518static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6519 QualType T,
Richard Smith958ba642013-05-05 15:51:06 +00006520 ArrayRef<Expr *> Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006521 OverloadCandidateSet &CandidateSet) {
6522 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00006523
Douglas Gregor19b7b152009-08-24 13:43:27 +00006524 // T& operator=(T&, T)
6525 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6526 ParamTypes[1] = T;
Richard Smith958ba642013-05-05 15:51:06 +00006527 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006528 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00006529
Douglas Gregor19b7b152009-08-24 13:43:27 +00006530 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6531 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00006532 ParamTypes[0]
6533 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00006534 ParamTypes[1] = T;
Richard Smith958ba642013-05-05 15:51:06 +00006535 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00006536 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00006537 }
6538}
Mike Stump1eb44332009-09-09 15:08:12 +00006539
Sebastian Redl9994a342009-10-25 17:03:50 +00006540/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6541/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006542static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6543 Qualifiers VRQuals;
6544 const RecordType *TyRec;
6545 if (const MemberPointerType *RHSMPType =
6546 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00006547 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006548 else
6549 TyRec = ArgExpr->getType()->getAs<RecordType>();
6550 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006551 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006552 VRQuals.addVolatile();
6553 VRQuals.addRestrict();
6554 return VRQuals;
6555 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006556
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006557 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00006558 if (!ClassDecl->hasDefinition())
6559 return VRQuals;
6560
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006561 std::pair<CXXRecordDecl::conversion_iterator,
6562 CXXRecordDecl::conversion_iterator>
6563 Conversions = ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006564
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006565 for (CXXRecordDecl::conversion_iterator
6566 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00006567 NamedDecl *D = I.getDecl();
6568 if (isa<UsingShadowDecl>(D))
6569 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6570 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006571 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6572 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6573 CanTy = ResTypeRef->getPointeeType();
6574 // Need to go down the pointer/mempointer chain and add qualifiers
6575 // as see them.
6576 bool done = false;
6577 while (!done) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006578 if (CanTy.isRestrictQualified())
6579 VRQuals.addRestrict();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006580 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6581 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006582 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006583 CanTy->getAs<MemberPointerType>())
6584 CanTy = ResTypeMPtr->getPointeeType();
6585 else
6586 done = true;
6587 if (CanTy.isVolatileQualified())
6588 VRQuals.addVolatile();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006589 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6590 return VRQuals;
6591 }
6592 }
6593 }
6594 return VRQuals;
6595}
John McCall00071ec2010-11-13 05:51:15 +00006596
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006597namespace {
John McCall00071ec2010-11-13 05:51:15 +00006598
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006599/// \brief Helper class to manage the addition of builtin operator overload
6600/// candidates. It provides shared state and utility methods used throughout
6601/// the process, as well as a helper method to add each group of builtin
6602/// operator overloads from the standard to a candidate set.
6603class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00006604 // Common instance state available to all overload candidate addition methods.
6605 Sema &S;
Richard Smith958ba642013-05-05 15:51:06 +00006606 ArrayRef<Expr *> Args;
Chandler Carruth6d695582010-12-12 10:35:00 +00006607 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00006608 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006609 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruth6d695582010-12-12 10:35:00 +00006610 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006611
Chandler Carruth6d695582010-12-12 10:35:00 +00006612 // Define some constants used to index and iterate over the arithemetic types
6613 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00006614 // The "promoted arithmetic types" are the arithmetic
6615 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00006616 static const unsigned FirstIntegralType = 3;
Richard Smith3c2fcf82012-06-10 08:00:26 +00006617 static const unsigned LastIntegralType = 20;
John McCall00071ec2010-11-13 05:51:15 +00006618 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006619 LastPromotedIntegralType = 11;
John McCall00071ec2010-11-13 05:51:15 +00006620 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006621 LastPromotedArithmeticType = 11;
6622 static const unsigned NumArithmeticTypes = 20;
John McCall00071ec2010-11-13 05:51:15 +00006623
Chandler Carruth6d695582010-12-12 10:35:00 +00006624 /// \brief Get the canonical type for a given arithmetic type index.
6625 CanQualType getArithmeticType(unsigned index) {
6626 assert(index < NumArithmeticTypes);
6627 static CanQualType ASTContext::* const
6628 ArithmeticTypes[NumArithmeticTypes] = {
6629 // Start of promoted types.
6630 &ASTContext::FloatTy,
6631 &ASTContext::DoubleTy,
6632 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00006633
Chandler Carruth6d695582010-12-12 10:35:00 +00006634 // Start of integral types.
6635 &ASTContext::IntTy,
6636 &ASTContext::LongTy,
6637 &ASTContext::LongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006638 &ASTContext::Int128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006639 &ASTContext::UnsignedIntTy,
6640 &ASTContext::UnsignedLongTy,
6641 &ASTContext::UnsignedLongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006642 &ASTContext::UnsignedInt128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006643 // End of promoted types.
6644
6645 &ASTContext::BoolTy,
6646 &ASTContext::CharTy,
6647 &ASTContext::WCharTy,
6648 &ASTContext::Char16Ty,
6649 &ASTContext::Char32Ty,
6650 &ASTContext::SignedCharTy,
6651 &ASTContext::ShortTy,
6652 &ASTContext::UnsignedCharTy,
6653 &ASTContext::UnsignedShortTy,
6654 // End of integral types.
Richard Smith3c2fcf82012-06-10 08:00:26 +00006655 // FIXME: What about complex? What about half?
Chandler Carruth6d695582010-12-12 10:35:00 +00006656 };
6657 return S.Context.*ArithmeticTypes[index];
6658 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006659
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006660 /// \brief Gets the canonical type resulting from the usual arithemetic
6661 /// converions for the given arithmetic types.
6662 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6663 // Accelerator table for performing the usual arithmetic conversions.
6664 // The rules are basically:
6665 // - if either is floating-point, use the wider floating-point
6666 // - if same signedness, use the higher rank
6667 // - if same size, use unsigned of the higher rank
6668 // - use the larger type
6669 // These rules, together with the axiom that higher ranks are
6670 // never smaller, are sufficient to precompute all of these results
6671 // *except* when dealing with signed types of higher rank.
6672 // (we could precompute SLL x UI for all known platforms, but it's
6673 // better not to make any assumptions).
Richard Smith3c2fcf82012-06-10 08:00:26 +00006674 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006675 enum PromotedType {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006676 Dep=-1,
6677 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006678 };
Nuno Lopes79e244f2012-04-21 14:45:25 +00006679 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006680 [LastPromotedArithmeticType] = {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006681/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6682/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6683/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6684/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6685/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6686/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6687/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6688/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6689/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6690/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6691/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006692 };
6693
6694 assert(L < LastPromotedArithmeticType);
6695 assert(R < LastPromotedArithmeticType);
6696 int Idx = ConversionsTable[L][R];
6697
6698 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00006699 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006700
6701 // Slow path: we need to compare widths.
6702 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00006703 CanQualType LT = getArithmeticType(L),
6704 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006705 unsigned LW = S.Context.getIntWidth(LT),
6706 RW = S.Context.getIntWidth(RT);
6707
6708 // If they're different widths, use the signed type.
6709 if (LW > RW) return LT;
6710 else if (LW < RW) return RT;
6711
6712 // Otherwise, use the unsigned type of the signed type's rank.
6713 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6714 assert(L == SLL || R == SLL);
6715 return S.Context.UnsignedLongLongTy;
6716 }
6717
Chandler Carruth3c69dc42010-12-12 09:22:45 +00006718 /// \brief Helper method to factor out the common pattern of adding overloads
6719 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006720 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006721 bool HasVolatile,
6722 bool HasRestrict) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006723 QualType ParamTypes[2] = {
6724 S.Context.getLValueReferenceType(CandidateTy),
6725 S.Context.IntTy
6726 };
6727
6728 // Non-volatile version.
Richard Smith958ba642013-05-05 15:51:06 +00006729 if (Args.size() == 1)
6730 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006731 else
Richard Smith958ba642013-05-05 15:51:06 +00006732 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006733
6734 // Use a heuristic to reduce number of builtin candidates in the set:
6735 // add volatile version only if there are conversions to a volatile type.
6736 if (HasVolatile) {
6737 ParamTypes[0] =
6738 S.Context.getLValueReferenceType(
6739 S.Context.getVolatileType(CandidateTy));
Richard Smith958ba642013-05-05 15:51:06 +00006740 if (Args.size() == 1)
6741 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006742 else
Richard Smith958ba642013-05-05 15:51:06 +00006743 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006744 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006745
6746 // Add restrict version only if there are conversions to a restrict type
6747 // and our candidate type is a non-restrict-qualified pointer.
6748 if (HasRestrict && CandidateTy->isAnyPointerType() &&
6749 !CandidateTy.isRestrictQualified()) {
6750 ParamTypes[0]
6751 = S.Context.getLValueReferenceType(
6752 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smith958ba642013-05-05 15:51:06 +00006753 if (Args.size() == 1)
6754 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006755 else
Richard Smith958ba642013-05-05 15:51:06 +00006756 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006757
6758 if (HasVolatile) {
6759 ParamTypes[0]
6760 = S.Context.getLValueReferenceType(
6761 S.Context.getCVRQualifiedType(CandidateTy,
6762 (Qualifiers::Volatile |
6763 Qualifiers::Restrict)));
Richard Smith958ba642013-05-05 15:51:06 +00006764 if (Args.size() == 1)
6765 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006766 else
Richard Smith958ba642013-05-05 15:51:06 +00006767 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006768 }
6769 }
6770
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006771 }
6772
6773public:
6774 BuiltinOperatorOverloadBuilder(
Richard Smith958ba642013-05-05 15:51:06 +00006775 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006776 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00006777 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006778 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006779 OverloadCandidateSet &CandidateSet)
Richard Smith958ba642013-05-05 15:51:06 +00006780 : S(S), Args(Args),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006781 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00006782 HasArithmeticOrEnumeralCandidateType(
6783 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006784 CandidateTypes(CandidateTypes),
6785 CandidateSet(CandidateSet) {
6786 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00006787 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006788 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006789 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006790 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006791 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006792 assert(getArithmeticType(FirstPromotedArithmeticType)
6793 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006794 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006795 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006796 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006797 "Invalid last promoted arithmetic type");
6798 }
6799
6800 // C++ [over.built]p3:
6801 //
6802 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6803 // is either volatile or empty, there exist candidate operator
6804 // functions of the form
6805 //
6806 // VQ T& operator++(VQ T&);
6807 // T operator++(VQ T&, int);
6808 //
6809 // C++ [over.built]p4:
6810 //
6811 // For every pair (T, VQ), where T is an arithmetic type other
6812 // than bool, and VQ is either volatile or empty, there exist
6813 // candidate operator functions of the form
6814 //
6815 // VQ T& operator--(VQ T&);
6816 // T operator--(VQ T&, int);
6817 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006818 if (!HasArithmeticOrEnumeralCandidateType)
6819 return;
6820
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006821 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6822 Arith < NumArithmeticTypes; ++Arith) {
6823 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00006824 getArithmeticType(Arith),
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006825 VisibleTypeConversionsQuals.hasVolatile(),
6826 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006827 }
6828 }
6829
6830 // C++ [over.built]p5:
6831 //
6832 // For every pair (T, VQ), where T is a cv-qualified or
6833 // cv-unqualified object type, and VQ is either volatile or
6834 // empty, there exist candidate operator functions of the form
6835 //
6836 // T*VQ& operator++(T*VQ&);
6837 // T*VQ& operator--(T*VQ&);
6838 // T* operator++(T*VQ&, int);
6839 // T* operator--(T*VQ&, int);
6840 void addPlusPlusMinusMinusPointerOverloads() {
6841 for (BuiltinCandidateTypeSet::iterator
6842 Ptr = CandidateTypes[0].pointer_begin(),
6843 PtrEnd = CandidateTypes[0].pointer_end();
6844 Ptr != PtrEnd; ++Ptr) {
6845 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006846 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006847 continue;
6848
6849 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006850 (!(*Ptr).isVolatileQualified() &&
6851 VisibleTypeConversionsQuals.hasVolatile()),
6852 (!(*Ptr).isRestrictQualified() &&
6853 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006854 }
6855 }
6856
6857 // C++ [over.built]p6:
6858 // For every cv-qualified or cv-unqualified object type T, there
6859 // exist candidate operator functions of the form
6860 //
6861 // T& operator*(T*);
6862 //
6863 // C++ [over.built]p7:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006864 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006865 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006866 // T& operator*(T*);
6867 void addUnaryStarPointerOverloads() {
6868 for (BuiltinCandidateTypeSet::iterator
6869 Ptr = CandidateTypes[0].pointer_begin(),
6870 PtrEnd = CandidateTypes[0].pointer_end();
6871 Ptr != PtrEnd; ++Ptr) {
6872 QualType ParamTy = *Ptr;
6873 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006874 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6875 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006876
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006877 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6878 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6879 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006880
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006881 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smith958ba642013-05-05 15:51:06 +00006882 &ParamTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006883 }
6884 }
6885
6886 // C++ [over.built]p9:
6887 // For every promoted arithmetic type T, there exist candidate
6888 // operator functions of the form
6889 //
6890 // T operator+(T);
6891 // T operator-(T);
6892 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006893 if (!HasArithmeticOrEnumeralCandidateType)
6894 return;
6895
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006896 for (unsigned Arith = FirstPromotedArithmeticType;
6897 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006898 QualType ArithTy = getArithmeticType(Arith);
Richard Smith958ba642013-05-05 15:51:06 +00006899 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006900 }
6901
6902 // Extension: We also add these operators for vector types.
6903 for (BuiltinCandidateTypeSet::iterator
6904 Vec = CandidateTypes[0].vector_begin(),
6905 VecEnd = CandidateTypes[0].vector_end();
6906 Vec != VecEnd; ++Vec) {
6907 QualType VecTy = *Vec;
Richard Smith958ba642013-05-05 15:51:06 +00006908 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006909 }
6910 }
6911
6912 // C++ [over.built]p8:
6913 // For every type T, there exist candidate operator functions of
6914 // the form
6915 //
6916 // T* operator+(T*);
6917 void addUnaryPlusPointerOverloads() {
6918 for (BuiltinCandidateTypeSet::iterator
6919 Ptr = CandidateTypes[0].pointer_begin(),
6920 PtrEnd = CandidateTypes[0].pointer_end();
6921 Ptr != PtrEnd; ++Ptr) {
6922 QualType ParamTy = *Ptr;
Richard Smith958ba642013-05-05 15:51:06 +00006923 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006924 }
6925 }
6926
6927 // C++ [over.built]p10:
6928 // For every promoted integral type T, there exist candidate
6929 // operator functions of the form
6930 //
6931 // T operator~(T);
6932 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006933 if (!HasArithmeticOrEnumeralCandidateType)
6934 return;
6935
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006936 for (unsigned Int = FirstPromotedIntegralType;
6937 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006938 QualType IntTy = getArithmeticType(Int);
Richard Smith958ba642013-05-05 15:51:06 +00006939 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006940 }
6941
6942 // Extension: We also add this operator for vector types.
6943 for (BuiltinCandidateTypeSet::iterator
6944 Vec = CandidateTypes[0].vector_begin(),
6945 VecEnd = CandidateTypes[0].vector_end();
6946 Vec != VecEnd; ++Vec) {
6947 QualType VecTy = *Vec;
Richard Smith958ba642013-05-05 15:51:06 +00006948 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006949 }
6950 }
6951
6952 // C++ [over.match.oper]p16:
6953 // For every pointer to member type T, there exist candidate operator
6954 // functions of the form
6955 //
6956 // bool operator==(T,T);
6957 // bool operator!=(T,T);
6958 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6959 /// Set of (canonical) types that we've already handled.
6960 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6961
Richard Smith958ba642013-05-05 15:51:06 +00006962 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006963 for (BuiltinCandidateTypeSet::iterator
6964 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6965 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6966 MemPtr != MemPtrEnd;
6967 ++MemPtr) {
6968 // Don't add the same builtin candidate twice.
6969 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6970 continue;
6971
6972 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smith958ba642013-05-05 15:51:06 +00006973 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006974 }
6975 }
6976 }
6977
6978 // C++ [over.built]p15:
6979 //
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006980 // For every T, where T is an enumeration type, a pointer type, or
6981 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006982 //
6983 // bool operator<(T, T);
6984 // bool operator>(T, T);
6985 // bool operator<=(T, T);
6986 // bool operator>=(T, T);
6987 // bool operator==(T, T);
6988 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006989 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman97c67392012-09-18 21:52:24 +00006990 // C++ [over.match.oper]p3:
6991 // [...]the built-in candidates include all of the candidate operator
6992 // functions defined in 13.6 that, compared to the given operator, [...]
6993 // do not have the same parameter-type-list as any non-template non-member
6994 // candidate.
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006995 //
Eli Friedman97c67392012-09-18 21:52:24 +00006996 // Note that in practice, this only affects enumeration types because there
6997 // aren't any built-in candidates of record type, and a user-defined operator
6998 // must have an operand of record or enumeration type. Also, the only other
6999 // overloaded operator with enumeration arguments, operator=,
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007000 // cannot be overloaded for enumeration types, so this is the only place
7001 // where we must suppress candidates like this.
7002 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7003 UserDefinedBinaryOperators;
7004
Richard Smith958ba642013-05-05 15:51:06 +00007005 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007006 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7007 CandidateTypes[ArgIdx].enumeration_end()) {
7008 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7009 CEnd = CandidateSet.end();
7010 C != CEnd; ++C) {
7011 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7012 continue;
7013
Eli Friedman97c67392012-09-18 21:52:24 +00007014 if (C->Function->isFunctionTemplateSpecialization())
7015 continue;
7016
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007017 QualType FirstParamType =
7018 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7019 QualType SecondParamType =
7020 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7021
7022 // Skip if either parameter isn't of enumeral type.
7023 if (!FirstParamType->isEnumeralType() ||
7024 !SecondParamType->isEnumeralType())
7025 continue;
7026
7027 // Add this operator to the set of known user-defined operators.
7028 UserDefinedBinaryOperators.insert(
7029 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7030 S.Context.getCanonicalType(SecondParamType)));
7031 }
7032 }
7033 }
7034
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007035 /// Set of (canonical) types that we've already handled.
7036 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7037
Richard Smith958ba642013-05-05 15:51:06 +00007038 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007039 for (BuiltinCandidateTypeSet::iterator
7040 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7041 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7042 Ptr != PtrEnd; ++Ptr) {
7043 // Don't add the same builtin candidate twice.
7044 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7045 continue;
7046
7047 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smith958ba642013-05-05 15:51:06 +00007048 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007049 }
7050 for (BuiltinCandidateTypeSet::iterator
7051 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7052 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7053 Enum != EnumEnd; ++Enum) {
7054 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7055
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007056 // Don't add the same builtin candidate twice, or if a user defined
7057 // candidate exists.
7058 if (!AddedTypes.insert(CanonType) ||
7059 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7060 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007061 continue;
7062
7063 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smith958ba642013-05-05 15:51:06 +00007064 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007065 }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00007066
7067 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7068 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7069 if (AddedTypes.insert(NullPtrTy) &&
Richard Smith958ba642013-05-05 15:51:06 +00007070 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00007071 NullPtrTy))) {
7072 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smith958ba642013-05-05 15:51:06 +00007073 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00007074 CandidateSet);
7075 }
7076 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007077 }
7078 }
7079
7080 // C++ [over.built]p13:
7081 //
7082 // For every cv-qualified or cv-unqualified object type T
7083 // there exist candidate operator functions of the form
7084 //
7085 // T* operator+(T*, ptrdiff_t);
7086 // T& operator[](T*, ptrdiff_t); [BELOW]
7087 // T* operator-(T*, ptrdiff_t);
7088 // T* operator+(ptrdiff_t, T*);
7089 // T& operator[](ptrdiff_t, T*); [BELOW]
7090 //
7091 // C++ [over.built]p14:
7092 //
7093 // For every T, where T is a pointer to object type, there
7094 // exist candidate operator functions of the form
7095 //
7096 // ptrdiff_t operator-(T, T);
7097 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7098 /// Set of (canonical) types that we've already handled.
7099 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7100
7101 for (int Arg = 0; Arg < 2; ++Arg) {
7102 QualType AsymetricParamTypes[2] = {
7103 S.Context.getPointerDiffType(),
7104 S.Context.getPointerDiffType(),
7105 };
7106 for (BuiltinCandidateTypeSet::iterator
7107 Ptr = CandidateTypes[Arg].pointer_begin(),
7108 PtrEnd = CandidateTypes[Arg].pointer_end();
7109 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007110 QualType PointeeTy = (*Ptr)->getPointeeType();
7111 if (!PointeeTy->isObjectType())
7112 continue;
7113
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007114 AsymetricParamTypes[Arg] = *Ptr;
7115 if (Arg == 0 || Op == OO_Plus) {
7116 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7117 // T* operator+(ptrdiff_t, T*);
Richard Smith958ba642013-05-05 15:51:06 +00007118 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007119 }
7120 if (Op == OO_Minus) {
7121 // ptrdiff_t operator-(T, T);
7122 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7123 continue;
7124
7125 QualType ParamTypes[2] = { *Ptr, *Ptr };
7126 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smith958ba642013-05-05 15:51:06 +00007127 Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007128 }
7129 }
7130 }
7131 }
7132
7133 // C++ [over.built]p12:
7134 //
7135 // For every pair of promoted arithmetic types L and R, there
7136 // exist candidate operator functions of the form
7137 //
7138 // LR operator*(L, R);
7139 // LR operator/(L, R);
7140 // LR operator+(L, R);
7141 // LR operator-(L, R);
7142 // bool operator<(L, R);
7143 // bool operator>(L, R);
7144 // bool operator<=(L, R);
7145 // bool operator>=(L, R);
7146 // bool operator==(L, R);
7147 // bool operator!=(L, R);
7148 //
7149 // where LR is the result of the usual arithmetic conversions
7150 // between types L and R.
7151 //
7152 // C++ [over.built]p24:
7153 //
7154 // For every pair of promoted arithmetic types L and R, there exist
7155 // candidate operator functions of the form
7156 //
7157 // LR operator?(bool, L, R);
7158 //
7159 // where LR is the result of the usual arithmetic conversions
7160 // between types L and R.
7161 // Our candidates ignore the first parameter.
7162 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007163 if (!HasArithmeticOrEnumeralCandidateType)
7164 return;
7165
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007166 for (unsigned Left = FirstPromotedArithmeticType;
7167 Left < LastPromotedArithmeticType; ++Left) {
7168 for (unsigned Right = FirstPromotedArithmeticType;
7169 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007170 QualType LandR[2] = { getArithmeticType(Left),
7171 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007172 QualType Result =
7173 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007174 : getUsualArithmeticConversions(Left, Right);
Richard Smith958ba642013-05-05 15:51:06 +00007175 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007176 }
7177 }
7178
7179 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7180 // conditional operator for vector types.
7181 for (BuiltinCandidateTypeSet::iterator
7182 Vec1 = CandidateTypes[0].vector_begin(),
7183 Vec1End = CandidateTypes[0].vector_end();
7184 Vec1 != Vec1End; ++Vec1) {
7185 for (BuiltinCandidateTypeSet::iterator
7186 Vec2 = CandidateTypes[1].vector_begin(),
7187 Vec2End = CandidateTypes[1].vector_end();
7188 Vec2 != Vec2End; ++Vec2) {
7189 QualType LandR[2] = { *Vec1, *Vec2 };
7190 QualType Result = S.Context.BoolTy;
7191 if (!isComparison) {
7192 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7193 Result = *Vec1;
7194 else
7195 Result = *Vec2;
7196 }
7197
Richard Smith958ba642013-05-05 15:51:06 +00007198 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007199 }
7200 }
7201 }
7202
7203 // C++ [over.built]p17:
7204 //
7205 // For every pair of promoted integral types L and R, there
7206 // exist candidate operator functions of the form
7207 //
7208 // LR operator%(L, R);
7209 // LR operator&(L, R);
7210 // LR operator^(L, R);
7211 // LR operator|(L, R);
7212 // L operator<<(L, R);
7213 // L operator>>(L, R);
7214 //
7215 // where LR is the result of the usual arithmetic conversions
7216 // between types L and R.
7217 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007218 if (!HasArithmeticOrEnumeralCandidateType)
7219 return;
7220
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007221 for (unsigned Left = FirstPromotedIntegralType;
7222 Left < LastPromotedIntegralType; ++Left) {
7223 for (unsigned Right = FirstPromotedIntegralType;
7224 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007225 QualType LandR[2] = { getArithmeticType(Left),
7226 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007227 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7228 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007229 : getUsualArithmeticConversions(Left, Right);
Richard Smith958ba642013-05-05 15:51:06 +00007230 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007231 }
7232 }
7233 }
7234
7235 // C++ [over.built]p20:
7236 //
7237 // For every pair (T, VQ), where T is an enumeration or
7238 // pointer to member type and VQ is either volatile or
7239 // empty, there exist candidate operator functions of the form
7240 //
7241 // VQ T& operator=(VQ T&, T);
7242 void addAssignmentMemberPointerOrEnumeralOverloads() {
7243 /// Set of (canonical) types that we've already handled.
7244 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7245
7246 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7247 for (BuiltinCandidateTypeSet::iterator
7248 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7249 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7250 Enum != EnumEnd; ++Enum) {
7251 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7252 continue;
7253
Richard Smith958ba642013-05-05 15:51:06 +00007254 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007255 }
7256
7257 for (BuiltinCandidateTypeSet::iterator
7258 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7259 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7260 MemPtr != MemPtrEnd; ++MemPtr) {
7261 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7262 continue;
7263
Richard Smith958ba642013-05-05 15:51:06 +00007264 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007265 }
7266 }
7267 }
7268
7269 // C++ [over.built]p19:
7270 //
7271 // For every pair (T, VQ), where T is any type and VQ is either
7272 // volatile or empty, there exist candidate operator functions
7273 // of the form
7274 //
7275 // T*VQ& operator=(T*VQ&, T*);
7276 //
7277 // C++ [over.built]p21:
7278 //
7279 // For every pair (T, VQ), where T is a cv-qualified or
7280 // cv-unqualified object type and VQ is either volatile or
7281 // empty, there exist candidate operator functions of the form
7282 //
7283 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7284 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7285 void addAssignmentPointerOverloads(bool isEqualOp) {
7286 /// Set of (canonical) types that we've already handled.
7287 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7288
7289 for (BuiltinCandidateTypeSet::iterator
7290 Ptr = CandidateTypes[0].pointer_begin(),
7291 PtrEnd = CandidateTypes[0].pointer_end();
7292 Ptr != PtrEnd; ++Ptr) {
7293 // If this is operator=, keep track of the builtin candidates we added.
7294 if (isEqualOp)
7295 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007296 else if (!(*Ptr)->getPointeeType()->isObjectType())
7297 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007298
7299 // non-volatile version
7300 QualType ParamTypes[2] = {
7301 S.Context.getLValueReferenceType(*Ptr),
7302 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7303 };
Richard Smith958ba642013-05-05 15:51:06 +00007304 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007305 /*IsAssigmentOperator=*/ isEqualOp);
7306
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007307 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7308 VisibleTypeConversionsQuals.hasVolatile();
7309 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007310 // volatile version
7311 ParamTypes[0] =
7312 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007313 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007314 /*IsAssigmentOperator=*/isEqualOp);
7315 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007316
7317 if (!(*Ptr).isRestrictQualified() &&
7318 VisibleTypeConversionsQuals.hasRestrict()) {
7319 // restrict version
7320 ParamTypes[0]
7321 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007322 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007323 /*IsAssigmentOperator=*/isEqualOp);
7324
7325 if (NeedVolatile) {
7326 // volatile restrict version
7327 ParamTypes[0]
7328 = S.Context.getLValueReferenceType(
7329 S.Context.getCVRQualifiedType(*Ptr,
7330 (Qualifiers::Volatile |
7331 Qualifiers::Restrict)));
Richard Smith958ba642013-05-05 15:51:06 +00007332 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007333 /*IsAssigmentOperator=*/isEqualOp);
7334 }
7335 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007336 }
7337
7338 if (isEqualOp) {
7339 for (BuiltinCandidateTypeSet::iterator
7340 Ptr = CandidateTypes[1].pointer_begin(),
7341 PtrEnd = CandidateTypes[1].pointer_end();
7342 Ptr != PtrEnd; ++Ptr) {
7343 // Make sure we don't add the same candidate twice.
7344 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7345 continue;
7346
Chandler Carruth6df868e2010-12-12 08:17:55 +00007347 QualType ParamTypes[2] = {
7348 S.Context.getLValueReferenceType(*Ptr),
7349 *Ptr,
7350 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007351
7352 // non-volatile version
Richard Smith958ba642013-05-05 15:51:06 +00007353 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007354 /*IsAssigmentOperator=*/true);
7355
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007356 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7357 VisibleTypeConversionsQuals.hasVolatile();
7358 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007359 // volatile version
7360 ParamTypes[0] =
7361 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007362 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7363 /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007364 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007365
7366 if (!(*Ptr).isRestrictQualified() &&
7367 VisibleTypeConversionsQuals.hasRestrict()) {
7368 // restrict version
7369 ParamTypes[0]
7370 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007371 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7372 /*IsAssigmentOperator=*/true);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007373
7374 if (NeedVolatile) {
7375 // volatile restrict version
7376 ParamTypes[0]
7377 = S.Context.getLValueReferenceType(
7378 S.Context.getCVRQualifiedType(*Ptr,
7379 (Qualifiers::Volatile |
7380 Qualifiers::Restrict)));
Richard Smith958ba642013-05-05 15:51:06 +00007381 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7382 /*IsAssigmentOperator=*/true);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007383 }
7384 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007385 }
7386 }
7387 }
7388
7389 // C++ [over.built]p18:
7390 //
7391 // For every triple (L, VQ, R), where L is an arithmetic type,
7392 // VQ is either volatile or empty, and R is a promoted
7393 // arithmetic type, there exist candidate operator functions of
7394 // the form
7395 //
7396 // VQ L& operator=(VQ L&, R);
7397 // VQ L& operator*=(VQ L&, R);
7398 // VQ L& operator/=(VQ L&, R);
7399 // VQ L& operator+=(VQ L&, R);
7400 // VQ L& operator-=(VQ L&, R);
7401 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007402 if (!HasArithmeticOrEnumeralCandidateType)
7403 return;
7404
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007405 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7406 for (unsigned Right = FirstPromotedArithmeticType;
7407 Right < LastPromotedArithmeticType; ++Right) {
7408 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007409 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007410
7411 // Add this built-in operator as a candidate (VQ is empty).
7412 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007413 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smith958ba642013-05-05 15:51:06 +00007414 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007415 /*IsAssigmentOperator=*/isEqualOp);
7416
7417 // Add this built-in operator as a candidate (VQ is 'volatile').
7418 if (VisibleTypeConversionsQuals.hasVolatile()) {
7419 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007420 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007421 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smith958ba642013-05-05 15:51:06 +00007422 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007423 /*IsAssigmentOperator=*/isEqualOp);
7424 }
7425 }
7426 }
7427
7428 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7429 for (BuiltinCandidateTypeSet::iterator
7430 Vec1 = CandidateTypes[0].vector_begin(),
7431 Vec1End = CandidateTypes[0].vector_end();
7432 Vec1 != Vec1End; ++Vec1) {
7433 for (BuiltinCandidateTypeSet::iterator
7434 Vec2 = CandidateTypes[1].vector_begin(),
7435 Vec2End = CandidateTypes[1].vector_end();
7436 Vec2 != Vec2End; ++Vec2) {
7437 QualType ParamTypes[2];
7438 ParamTypes[1] = *Vec2;
7439 // Add this built-in operator as a candidate (VQ is empty).
7440 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smith958ba642013-05-05 15:51:06 +00007441 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007442 /*IsAssigmentOperator=*/isEqualOp);
7443
7444 // Add this built-in operator as a candidate (VQ is 'volatile').
7445 if (VisibleTypeConversionsQuals.hasVolatile()) {
7446 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7447 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smith958ba642013-05-05 15:51:06 +00007448 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007449 /*IsAssigmentOperator=*/isEqualOp);
7450 }
7451 }
7452 }
7453 }
7454
7455 // C++ [over.built]p22:
7456 //
7457 // For every triple (L, VQ, R), where L is an integral type, VQ
7458 // is either volatile or empty, and R is a promoted integral
7459 // type, there exist candidate operator functions of the form
7460 //
7461 // VQ L& operator%=(VQ L&, R);
7462 // VQ L& operator<<=(VQ L&, R);
7463 // VQ L& operator>>=(VQ L&, R);
7464 // VQ L& operator&=(VQ L&, R);
7465 // VQ L& operator^=(VQ L&, R);
7466 // VQ L& operator|=(VQ L&, R);
7467 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00007468 if (!HasArithmeticOrEnumeralCandidateType)
7469 return;
7470
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007471 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7472 for (unsigned Right = FirstPromotedIntegralType;
7473 Right < LastPromotedIntegralType; ++Right) {
7474 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007475 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007476
7477 // Add this built-in operator as a candidate (VQ is empty).
7478 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007479 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smith958ba642013-05-05 15:51:06 +00007480 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007481 if (VisibleTypeConversionsQuals.hasVolatile()) {
7482 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00007483 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007484 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7485 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smith958ba642013-05-05 15:51:06 +00007486 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007487 }
7488 }
7489 }
7490 }
7491
7492 // C++ [over.operator]p23:
7493 //
7494 // There also exist candidate operator functions of the form
7495 //
7496 // bool operator!(bool);
7497 // bool operator&&(bool, bool);
7498 // bool operator||(bool, bool);
7499 void addExclaimOverload() {
7500 QualType ParamTy = S.Context.BoolTy;
Richard Smith958ba642013-05-05 15:51:06 +00007501 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007502 /*IsAssignmentOperator=*/false,
7503 /*NumContextualBoolArguments=*/1);
7504 }
7505 void addAmpAmpOrPipePipeOverload() {
7506 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smith958ba642013-05-05 15:51:06 +00007507 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007508 /*IsAssignmentOperator=*/false,
7509 /*NumContextualBoolArguments=*/2);
7510 }
7511
7512 // C++ [over.built]p13:
7513 //
7514 // For every cv-qualified or cv-unqualified object type T there
7515 // exist candidate operator functions of the form
7516 //
7517 // T* operator+(T*, ptrdiff_t); [ABOVE]
7518 // T& operator[](T*, ptrdiff_t);
7519 // T* operator-(T*, ptrdiff_t); [ABOVE]
7520 // T* operator+(ptrdiff_t, T*); [ABOVE]
7521 // T& operator[](ptrdiff_t, T*);
7522 void addSubscriptOverloads() {
7523 for (BuiltinCandidateTypeSet::iterator
7524 Ptr = CandidateTypes[0].pointer_begin(),
7525 PtrEnd = CandidateTypes[0].pointer_end();
7526 Ptr != PtrEnd; ++Ptr) {
7527 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7528 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007529 if (!PointeeType->isObjectType())
7530 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007531
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007532 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7533
7534 // T& operator[](T*, ptrdiff_t)
Richard Smith958ba642013-05-05 15:51:06 +00007535 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007536 }
7537
7538 for (BuiltinCandidateTypeSet::iterator
7539 Ptr = CandidateTypes[1].pointer_begin(),
7540 PtrEnd = CandidateTypes[1].pointer_end();
7541 Ptr != PtrEnd; ++Ptr) {
7542 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7543 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007544 if (!PointeeType->isObjectType())
7545 continue;
7546
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007547 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7548
7549 // T& operator[](ptrdiff_t, T*)
Richard Smith958ba642013-05-05 15:51:06 +00007550 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007551 }
7552 }
7553
7554 // C++ [over.built]p11:
7555 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7556 // C1 is the same type as C2 or is a derived class of C2, T is an object
7557 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7558 // there exist candidate operator functions of the form
7559 //
7560 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7561 //
7562 // where CV12 is the union of CV1 and CV2.
7563 void addArrowStarOverloads() {
7564 for (BuiltinCandidateTypeSet::iterator
7565 Ptr = CandidateTypes[0].pointer_begin(),
7566 PtrEnd = CandidateTypes[0].pointer_end();
7567 Ptr != PtrEnd; ++Ptr) {
7568 QualType C1Ty = (*Ptr);
7569 QualType C1;
7570 QualifierCollector Q1;
7571 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7572 if (!isa<RecordType>(C1))
7573 continue;
7574 // heuristic to reduce number of builtin candidates in the set.
7575 // Add volatile/restrict version only if there are conversions to a
7576 // volatile/restrict type.
7577 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7578 continue;
7579 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7580 continue;
7581 for (BuiltinCandidateTypeSet::iterator
7582 MemPtr = CandidateTypes[1].member_pointer_begin(),
7583 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7584 MemPtr != MemPtrEnd; ++MemPtr) {
7585 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7586 QualType C2 = QualType(mptr->getClass(), 0);
7587 C2 = C2.getUnqualifiedType();
7588 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7589 break;
7590 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7591 // build CV12 T&
7592 QualType T = mptr->getPointeeType();
7593 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7594 T.isVolatileQualified())
7595 continue;
7596 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7597 T.isRestrictQualified())
7598 continue;
7599 T = Q1.apply(S.Context, T);
7600 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smith958ba642013-05-05 15:51:06 +00007601 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007602 }
7603 }
7604 }
7605
7606 // Note that we don't consider the first argument, since it has been
7607 // contextually converted to bool long ago. The candidates below are
7608 // therefore added as binary.
7609 //
7610 // C++ [over.built]p25:
7611 // For every type T, where T is a pointer, pointer-to-member, or scoped
7612 // enumeration type, there exist candidate operator functions of the form
7613 //
7614 // T operator?(bool, T, T);
7615 //
7616 void addConditionalOperatorOverloads() {
7617 /// Set of (canonical) types that we've already handled.
7618 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7619
7620 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7621 for (BuiltinCandidateTypeSet::iterator
7622 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7623 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7624 Ptr != PtrEnd; ++Ptr) {
7625 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7626 continue;
7627
7628 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smith958ba642013-05-05 15:51:06 +00007629 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007630 }
7631
7632 for (BuiltinCandidateTypeSet::iterator
7633 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7634 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7635 MemPtr != MemPtrEnd; ++MemPtr) {
7636 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7637 continue;
7638
7639 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smith958ba642013-05-05 15:51:06 +00007640 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007641 }
7642
Richard Smith80ad52f2013-01-02 11:42:31 +00007643 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007644 for (BuiltinCandidateTypeSet::iterator
7645 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7646 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7647 Enum != EnumEnd; ++Enum) {
7648 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7649 continue;
7650
7651 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7652 continue;
7653
7654 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smith958ba642013-05-05 15:51:06 +00007655 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007656 }
7657 }
7658 }
7659 }
7660};
7661
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007662} // end anonymous namespace
7663
7664/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7665/// operator overloads to the candidate set (C++ [over.built]), based
7666/// on the operator @p Op and the arguments given. For example, if the
7667/// operator is a binary '+', this routine might add "int
7668/// operator+(int, int)" to cover integer addition.
7669void
7670Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7671 SourceLocation OpLoc,
Richard Smith958ba642013-05-05 15:51:06 +00007672 llvm::ArrayRef<Expr *> Args,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007673 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007674 // Find all of the types that the arguments can convert to, but only
7675 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00007676 // that make use of these types. Also record whether we encounter non-record
7677 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00007678 Qualifiers VisibleTypeConversionsQuals;
7679 VisibleTypeConversionsQuals.addConst();
Richard Smith958ba642013-05-05 15:51:06 +00007680 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanian8621d012009-10-19 21:30:45 +00007681 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00007682
7683 bool HasNonRecordCandidateType = false;
7684 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00007685 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smith958ba642013-05-05 15:51:06 +00007686 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorfec56e72010-11-03 17:00:07 +00007687 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7688 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7689 OpLoc,
7690 true,
7691 (Op == OO_Exclaim ||
7692 Op == OO_AmpAmp ||
7693 Op == OO_PipePipe),
7694 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00007695 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7696 CandidateTypes[ArgIdx].hasNonRecordTypes();
7697 HasArithmeticOrEnumeralCandidateType =
7698 HasArithmeticOrEnumeralCandidateType ||
7699 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00007700 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007701
Chandler Carruth6a577462010-12-13 01:44:01 +00007702 // Exit early when no non-record types have been added to the candidate set
7703 // for any of the arguments to the operator.
Douglas Gregor25aaff92011-10-10 14:05:31 +00007704 //
7705 // We can't exit early for !, ||, or &&, since there we have always have
7706 // 'bool' overloads.
Richard Smith958ba642013-05-05 15:51:06 +00007707 if (!HasNonRecordCandidateType &&
Douglas Gregor25aaff92011-10-10 14:05:31 +00007708 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth6a577462010-12-13 01:44:01 +00007709 return;
7710
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007711 // Setup an object to manage the common state for building overloads.
Richard Smith958ba642013-05-05 15:51:06 +00007712 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007713 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00007714 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007715 CandidateTypes, CandidateSet);
7716
7717 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007718 switch (Op) {
7719 case OO_None:
7720 case NUM_OVERLOADED_OPERATORS:
David Blaikieb219cfc2011-09-23 05:06:16 +00007721 llvm_unreachable("Expected an overloaded operator");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007722
Chandler Carruthabb71842010-12-12 08:51:33 +00007723 case OO_New:
7724 case OO_Delete:
7725 case OO_Array_New:
7726 case OO_Array_Delete:
7727 case OO_Call:
David Blaikieb219cfc2011-09-23 05:06:16 +00007728 llvm_unreachable(
7729 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruthabb71842010-12-12 08:51:33 +00007730
7731 case OO_Comma:
7732 case OO_Arrow:
7733 // C++ [over.match.oper]p3:
7734 // -- For the operator ',', the unary operator '&', or the
7735 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00007736 break;
7737
7738 case OO_Plus: // '+' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007739 if (Args.size() == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007740 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007741 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00007742
7743 case OO_Minus: // '-' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007744 if (Args.size() == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007745 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007746 } else {
7747 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7748 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7749 }
Douglas Gregor74253732008-11-19 15:42:04 +00007750 break;
7751
Chandler Carruthabb71842010-12-12 08:51:33 +00007752 case OO_Star: // '*' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007753 if (Args.size() == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007754 OpBuilder.addUnaryStarPointerOverloads();
7755 else
7756 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7757 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007758
Chandler Carruthabb71842010-12-12 08:51:33 +00007759 case OO_Slash:
7760 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00007761 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007762
7763 case OO_PlusPlus:
7764 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007765 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7766 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00007767 break;
7768
Douglas Gregor19b7b152009-08-24 13:43:27 +00007769 case OO_EqualEqual:
7770 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007771 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007772 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00007773
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007774 case OO_Less:
7775 case OO_Greater:
7776 case OO_LessEqual:
7777 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007778 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007779 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7780 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007781
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007782 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007783 case OO_Caret:
7784 case OO_Pipe:
7785 case OO_LessLess:
7786 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007787 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007788 break;
7789
Chandler Carruthabb71842010-12-12 08:51:33 +00007790 case OO_Amp: // '&' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007791 if (Args.size() == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007792 // C++ [over.match.oper]p3:
7793 // -- For the operator ',', the unary operator '&', or the
7794 // operator '->', the built-in candidates set is empty.
7795 break;
7796
7797 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7798 break;
7799
7800 case OO_Tilde:
7801 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7802 break;
7803
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007804 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007805 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00007806 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007807
7808 case OO_PlusEqual:
7809 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007810 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007811 // Fall through.
7812
7813 case OO_StarEqual:
7814 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007815 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007816 break;
7817
7818 case OO_PercentEqual:
7819 case OO_LessLessEqual:
7820 case OO_GreaterGreaterEqual:
7821 case OO_AmpEqual:
7822 case OO_CaretEqual:
7823 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007824 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007825 break;
7826
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007827 case OO_Exclaim:
7828 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00007829 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007830
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007831 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007832 case OO_PipePipe:
7833 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007834 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007835
7836 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007837 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007838 break;
7839
7840 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007841 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007842 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007843
7844 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007845 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007846 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7847 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007848 }
7849}
7850
Douglas Gregorfa047642009-02-04 00:32:51 +00007851/// \brief Add function candidates found via argument-dependent lookup
7852/// to the set of overloading candidates.
7853///
7854/// This routine performs argument-dependent name lookup based on the
7855/// given function name (which may also be an operator name) and adds
7856/// all of the overload candidates found by ADL to the overload
7857/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00007858void
Douglas Gregorfa047642009-02-04 00:32:51 +00007859Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00007860 bool Operator, SourceLocation Loc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00007861 ArrayRef<Expr *> Args,
Douglas Gregor67714232011-03-03 02:41:12 +00007862 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007863 OverloadCandidateSet& CandidateSet,
Richard Smithb1502bc2012-10-18 17:56:02 +00007864 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00007865 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00007866
John McCalla113e722010-01-26 06:04:06 +00007867 // FIXME: This approach for uniquing ADL results (and removing
7868 // redundant candidates from the set) relies on pointer-equality,
7869 // which means we need to key off the canonical decl. However,
7870 // always going back to the canonical decl might not get us the
7871 // right set of default arguments. What default arguments are
7872 // we supposed to consider on ADL candidates, anyway?
7873
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007874 // FIXME: Pass in the explicit template arguments?
Richard Smithb1502bc2012-10-18 17:56:02 +00007875 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00007876
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007877 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007878 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7879 CandEnd = CandidateSet.end();
7880 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00007881 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00007882 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00007883 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00007884 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00007885 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007886
7887 // For each of the ADL candidates we found, add it to the overload
7888 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00007889 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00007890 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00007891 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00007892 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007893 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007894
Ahmed Charles13a140c2012-02-25 11:00:22 +00007895 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7896 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007897 } else
John McCall6e266892010-01-26 03:27:55 +00007898 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00007899 FoundDecl, ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00007900 Args, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00007901 }
Douglas Gregorfa047642009-02-04 00:32:51 +00007902}
7903
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007904/// isBetterOverloadCandidate - Determines whether the first overload
7905/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00007906bool
John McCall120d63c2010-08-24 20:38:10 +00007907isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00007908 const OverloadCandidate &Cand1,
7909 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007910 SourceLocation Loc,
7911 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007912 // Define viable functions to be better candidates than non-viable
7913 // functions.
7914 if (!Cand2.Viable)
7915 return Cand1.Viable;
7916 else if (!Cand1.Viable)
7917 return false;
7918
Douglas Gregor88a35142008-12-22 05:46:06 +00007919 // C++ [over.match.best]p1:
7920 //
7921 // -- if F is a static member function, ICS1(F) is defined such
7922 // that ICS1(F) is neither better nor worse than ICS1(G) for
7923 // any function G, and, symmetrically, ICS1(G) is neither
7924 // better nor worse than ICS1(F).
7925 unsigned StartArg = 0;
7926 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7927 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007928
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007929 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00007930 // A viable function F1 is defined to be a better function than another
7931 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007932 // conversion sequence than ICSi(F2), and then...
Benjamin Kramer09dd3792012-01-14 16:32:05 +00007933 unsigned NumArgs = Cand1.NumConversions;
7934 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007935 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00007936 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00007937 switch (CompareImplicitConversionSequences(S,
7938 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007939 Cand2.Conversions[ArgIdx])) {
7940 case ImplicitConversionSequence::Better:
7941 // Cand1 has a better conversion sequence.
7942 HasBetterConversion = true;
7943 break;
7944
7945 case ImplicitConversionSequence::Worse:
7946 // Cand1 can't be better than Cand2.
7947 return false;
7948
7949 case ImplicitConversionSequence::Indistinguishable:
7950 // Do nothing.
7951 break;
7952 }
7953 }
7954
Mike Stump1eb44332009-09-09 15:08:12 +00007955 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007956 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007957 if (HasBetterConversion)
7958 return true;
7959
Mike Stump1eb44332009-09-09 15:08:12 +00007960 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007961 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00007962 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007963 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7964 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00007965
7966 // -- F1 and F2 are function template specializations, and the function
7967 // template for F1 is more specialized than the template for F2
7968 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007969 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00007970 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregordfc331e2011-01-19 23:54:39 +00007971 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007972 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00007973 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7974 Cand2.Function->getPrimaryTemplate(),
7975 Loc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007976 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00007977 : TPOC_Call,
Douglas Gregordfc331e2011-01-19 23:54:39 +00007978 Cand1.ExplicitCallArguments))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007979 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregordfc331e2011-01-19 23:54:39 +00007980 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007981
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007982 // -- the context is an initialization by user-defined conversion
7983 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7984 // from the return type of F1 to the destination type (i.e.,
7985 // the type of the entity being initialized) is a better
7986 // conversion sequence than the standard conversion sequence
7987 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007988 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00007989 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007990 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregorb734e242012-02-22 17:32:19 +00007991 // First check whether we prefer one of the conversion functions over the
7992 // other. This only distinguishes the results in non-standard, extension
7993 // cases such as the conversion from a lambda closure type to a function
7994 // pointer or block.
7995 ImplicitConversionSequence::CompareKind FuncResult
7996 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7997 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7998 return FuncResult;
7999
John McCall120d63c2010-08-24 20:38:10 +00008000 switch (CompareStandardConversionSequences(S,
8001 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00008002 Cand2.FinalConversion)) {
8003 case ImplicitConversionSequence::Better:
8004 // Cand1 has a better conversion sequence.
8005 return true;
8006
8007 case ImplicitConversionSequence::Worse:
8008 // Cand1 can't be better than Cand2.
8009 return false;
8010
8011 case ImplicitConversionSequence::Indistinguishable:
8012 // Do nothing
8013 break;
8014 }
8015 }
8016
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008017 return false;
8018}
8019
Mike Stump1eb44332009-09-09 15:08:12 +00008020/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00008021/// within an overload candidate set.
8022///
James Dennettefce31f2012-06-22 08:10:18 +00008023/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregore0762c92009-06-19 23:52:42 +00008024/// which overload resolution occurs.
8025///
James Dennettefce31f2012-06-22 08:10:18 +00008026/// \param Best If overload resolution was successful or found a deleted
8027/// function, \p Best points to the candidate function found.
Douglas Gregore0762c92009-06-19 23:52:42 +00008028///
8029/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00008030OverloadingResult
8031OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00008032 iterator &Best,
Chandler Carruth25ca4212011-02-25 19:41:05 +00008033 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008034 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00008035 Best = end();
8036 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8037 if (Cand->Viable)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008038 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00008039 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008040 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008041 }
8042
8043 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00008044 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008045 return OR_No_Viable_Function;
8046
8047 // Make sure that this function is better than every other viable
8048 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00008049 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00008050 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008051 Cand != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008052 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00008053 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00008054 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008055 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008056 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008057 }
Mike Stump1eb44332009-09-09 15:08:12 +00008058
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008059 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008060 if (Best->Function &&
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008061 (Best->Function->isDeleted() ||
8062 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008063 return OR_Deleted;
8064
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008065 return OR_Success;
8066}
8067
John McCall3c80f572010-01-12 02:15:36 +00008068namespace {
8069
8070enum OverloadCandidateKind {
8071 oc_function,
8072 oc_method,
8073 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00008074 oc_function_template,
8075 oc_method_template,
8076 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00008077 oc_implicit_default_constructor,
8078 oc_implicit_copy_constructor,
Sean Hunt82713172011-05-25 23:16:36 +00008079 oc_implicit_move_constructor,
Sebastian Redlf677ea32011-02-05 19:23:19 +00008080 oc_implicit_copy_assignment,
Sean Hunt82713172011-05-25 23:16:36 +00008081 oc_implicit_move_assignment,
Sebastian Redlf677ea32011-02-05 19:23:19 +00008082 oc_implicit_inherited_constructor
John McCall3c80f572010-01-12 02:15:36 +00008083};
8084
John McCall220ccbf2010-01-13 00:25:19 +00008085OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8086 FunctionDecl *Fn,
8087 std::string &Description) {
8088 bool isTemplate = false;
8089
8090 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8091 isTemplate = true;
8092 Description = S.getTemplateArgumentBindingsText(
8093 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8094 }
John McCallb1622a12010-01-06 09:43:14 +00008095
8096 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00008097 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00008098 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00008099
Sebastian Redlf677ea32011-02-05 19:23:19 +00008100 if (Ctor->getInheritedConstructor())
8101 return oc_implicit_inherited_constructor;
8102
Sean Hunt82713172011-05-25 23:16:36 +00008103 if (Ctor->isDefaultConstructor())
8104 return oc_implicit_default_constructor;
8105
8106 if (Ctor->isMoveConstructor())
8107 return oc_implicit_move_constructor;
8108
8109 assert(Ctor->isCopyConstructor() &&
8110 "unexpected sort of implicit constructor");
8111 return oc_implicit_copy_constructor;
John McCallb1622a12010-01-06 09:43:14 +00008112 }
8113
8114 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8115 // This actually gets spelled 'candidate function' for now, but
8116 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00008117 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00008118 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00008119
Sean Hunt82713172011-05-25 23:16:36 +00008120 if (Meth->isMoveAssignmentOperator())
8121 return oc_implicit_move_assignment;
8122
Douglas Gregoref7d78b2012-02-10 08:36:38 +00008123 if (Meth->isCopyAssignmentOperator())
8124 return oc_implicit_copy_assignment;
8125
8126 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8127 return oc_method;
John McCall3c80f572010-01-12 02:15:36 +00008128 }
8129
John McCall220ccbf2010-01-13 00:25:19 +00008130 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00008131}
8132
Larisse Voufo43847122013-07-19 23:00:19 +00008133void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
Sebastian Redlf677ea32011-02-05 19:23:19 +00008134 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8135 if (!Ctor) return;
8136
8137 Ctor = Ctor->getInheritedConstructor();
8138 if (!Ctor) return;
8139
8140 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8141}
8142
John McCall3c80f572010-01-12 02:15:36 +00008143} // end anonymous namespace
8144
8145// Notes the location of an overload candidate.
Richard Trieu6efd4c52011-11-23 22:32:32 +00008146void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCall220ccbf2010-01-13 00:25:19 +00008147 std::string FnDesc;
8148 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieu6efd4c52011-11-23 22:32:32 +00008149 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8150 << (unsigned) K << FnDesc;
8151 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8152 Diag(Fn->getLocation(), PD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008153 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallb1622a12010-01-06 09:43:14 +00008154}
8155
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008156//Notes the location of all overload candidates designated through
8157// OverloadedExpr
Richard Trieu6efd4c52011-11-23 22:32:32 +00008158void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008159 assert(OverloadedExpr->getType() == Context.OverloadTy);
8160
8161 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8162 OverloadExpr *OvlExpr = Ovl.Expression;
8163
8164 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8165 IEnd = OvlExpr->decls_end();
8166 I != IEnd; ++I) {
8167 if (FunctionTemplateDecl *FunTmpl =
8168 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00008169 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008170 } else if (FunctionDecl *Fun
8171 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00008172 NoteOverloadCandidate(Fun, DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008173 }
8174 }
8175}
8176
John McCall1d318332010-01-12 00:44:57 +00008177/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8178/// "lead" diagnostic; it will be given two arguments, the source and
8179/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00008180void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8181 Sema &S,
8182 SourceLocation CaretLoc,
8183 const PartialDiagnostic &PDiag) const {
8184 S.Diag(CaretLoc, PDiag)
8185 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay45a37da2012-11-08 20:50:02 +00008186 // FIXME: The note limiting machinery is borrowed from
8187 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8188 // refactoring here.
8189 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8190 unsigned CandsShown = 0;
8191 AmbiguousConversionSequence::const_iterator I, E;
8192 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8193 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8194 break;
8195 ++CandsShown;
John McCall120d63c2010-08-24 20:38:10 +00008196 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00008197 }
Matt Beaumont-Gay45a37da2012-11-08 20:50:02 +00008198 if (I != E)
8199 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall81201622010-01-08 04:41:39 +00008200}
8201
John McCall1d318332010-01-12 00:44:57 +00008202namespace {
8203
John McCalladbb8f82010-01-13 09:16:55 +00008204void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8205 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8206 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00008207 assert(Cand->Function && "for now, candidate must be a function");
8208 FunctionDecl *Fn = Cand->Function;
8209
8210 // There's a conversion slot for the object argument if this is a
8211 // non-constructor method. Note that 'I' corresponds the
8212 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00008213 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00008214 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00008215 if (I == 0)
8216 isObjectArgument = true;
8217 else
8218 I--;
John McCall220ccbf2010-01-13 00:25:19 +00008219 }
8220
John McCall220ccbf2010-01-13 00:25:19 +00008221 std::string FnDesc;
8222 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8223
John McCalladbb8f82010-01-13 09:16:55 +00008224 Expr *FromExpr = Conv.Bad.FromExpr;
8225 QualType FromTy = Conv.Bad.getFromType();
8226 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00008227
John McCall5920dbb2010-02-02 02:42:52 +00008228 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00008229 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00008230 Expr *E = FromExpr->IgnoreParens();
8231 if (isa<UnaryOperator>(E))
8232 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00008233 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00008234
8235 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8236 << (unsigned) FnKind << FnDesc
8237 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8238 << ToTy << Name << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008239 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall5920dbb2010-02-02 02:42:52 +00008240 return;
8241 }
8242
John McCall258b2032010-01-23 08:10:49 +00008243 // Do some hand-waving analysis to see if the non-viability is due
8244 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00008245 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8246 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8247 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8248 CToTy = RT->getPointeeType();
8249 else {
8250 // TODO: detect and diagnose the full richness of const mismatches.
8251 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8252 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8253 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8254 }
8255
8256 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8257 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall651f3ee2010-01-14 03:28:57 +00008258 Qualifiers FromQs = CFromTy.getQualifiers();
8259 Qualifiers ToQs = CToTy.getQualifiers();
8260
8261 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8262 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8263 << (unsigned) FnKind << FnDesc
8264 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8265 << FromTy
8266 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8267 << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008268 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008269 return;
8270 }
8271
John McCallf85e1932011-06-15 23:02:42 +00008272 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00008273 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCallf85e1932011-06-15 23:02:42 +00008274 << (unsigned) FnKind << FnDesc
8275 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8276 << FromTy
8277 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8278 << (unsigned) isObjectArgument << I+1;
8279 MaybeEmitInheritedConstructorNote(S, Fn);
8280 return;
8281 }
8282
Douglas Gregor028ea4b2011-04-26 23:16:46 +00008283 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8284 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8285 << (unsigned) FnKind << FnDesc
8286 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8287 << FromTy
8288 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8289 << (unsigned) isObjectArgument << I+1;
8290 MaybeEmitInheritedConstructorNote(S, Fn);
8291 return;
8292 }
8293
John McCall651f3ee2010-01-14 03:28:57 +00008294 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8295 assert(CVR && "unexpected qualifiers mismatch");
8296
8297 if (isObjectArgument) {
8298 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8299 << (unsigned) FnKind << FnDesc
8300 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8301 << FromTy << (CVR - 1);
8302 } else {
8303 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8304 << (unsigned) FnKind << FnDesc
8305 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8306 << FromTy << (CVR - 1) << I+1;
8307 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008308 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008309 return;
8310 }
8311
Sebastian Redlfd2a00a2011-09-24 17:48:32 +00008312 // Special diagnostic for failure to convert an initializer list, since
8313 // telling the user that it has type void is not useful.
8314 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8315 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8316 << (unsigned) FnKind << FnDesc
8317 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8318 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8319 MaybeEmitInheritedConstructorNote(S, Fn);
8320 return;
8321 }
8322
John McCall258b2032010-01-23 08:10:49 +00008323 // Diagnose references or pointers to incomplete types differently,
8324 // since it's far from impossible that the incompleteness triggered
8325 // the failure.
8326 QualType TempFromTy = FromTy.getNonReferenceType();
8327 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8328 TempFromTy = PTy->getPointeeType();
8329 if (TempFromTy->isIncompleteType()) {
8330 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8331 << (unsigned) FnKind << FnDesc
8332 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8333 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008334 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall258b2032010-01-23 08:10:49 +00008335 return;
8336 }
8337
Douglas Gregor85789812010-06-30 23:01:39 +00008338 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008339 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00008340 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8341 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8342 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8343 FromPtrTy->getPointeeType()) &&
8344 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8345 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008346 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor85789812010-06-30 23:01:39 +00008347 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008348 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00008349 }
8350 } else if (const ObjCObjectPointerType *FromPtrTy
8351 = FromTy->getAs<ObjCObjectPointerType>()) {
8352 if (const ObjCObjectPointerType *ToPtrTy
8353 = ToTy->getAs<ObjCObjectPointerType>())
8354 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8355 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8356 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8357 FromPtrTy->getPointeeType()) &&
8358 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008359 BaseToDerivedConversion = 2;
8360 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008361 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8362 !FromTy->isIncompleteType() &&
8363 !ToRefTy->getPointeeType()->isIncompleteType() &&
8364 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8365 BaseToDerivedConversion = 3;
8366 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8367 ToTy.getNonReferenceType().getCanonicalType() ==
8368 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008369 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8370 << (unsigned) FnKind << FnDesc
8371 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8372 << (unsigned) isObjectArgument << I + 1;
8373 MaybeEmitInheritedConstructorNote(S, Fn);
8374 return;
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008375 }
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008376 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008377
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008378 if (BaseToDerivedConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008379 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008380 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00008381 << (unsigned) FnKind << FnDesc
8382 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008383 << (BaseToDerivedConversion - 1)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008384 << FromTy << ToTy << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008385 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor85789812010-06-30 23:01:39 +00008386 return;
8387 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008388
Fariborz Jahanian909bcb32011-07-20 17:14:09 +00008389 if (isa<ObjCObjectPointerType>(CFromTy) &&
8390 isa<PointerType>(CToTy)) {
8391 Qualifiers FromQs = CFromTy.getQualifiers();
8392 Qualifiers ToQs = CToTy.getQualifiers();
8393 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8394 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8395 << (unsigned) FnKind << FnDesc
8396 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8397 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8398 MaybeEmitInheritedConstructorNote(S, Fn);
8399 return;
8400 }
8401 }
8402
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008403 // Emit the generic diagnostic and, optionally, add the hints to it.
8404 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8405 FDiag << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00008406 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008407 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8408 << (unsigned) (Cand->Fix.Kind);
8409
8410 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer1136ef02012-01-14 21:05:10 +00008411 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8412 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008413 FDiag << *HI;
8414 S.Diag(Fn->getLocation(), FDiag);
8415
Sebastian Redlf677ea32011-02-05 19:23:19 +00008416 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalladbb8f82010-01-13 09:16:55 +00008417}
8418
Larisse Voufo43847122013-07-19 23:00:19 +00008419/// Additional arity mismatch diagnosis specific to a function overload
8420/// candidates. This is not covered by the more general DiagnoseArityMismatch()
8421/// over a candidate in any candidate set.
8422bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8423 unsigned NumArgs) {
John McCalladbb8f82010-01-13 09:16:55 +00008424 FunctionDecl *Fn = Cand->Function;
John McCalladbb8f82010-01-13 09:16:55 +00008425 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008426
Douglas Gregor439d3c32011-05-05 00:13:13 +00008427 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo43847122013-07-19 23:00:19 +00008428 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor439d3c32011-05-05 00:13:13 +00008429 // right number of arguments, because only overloaded operators have
8430 // the weird behavior of overloading member and non-member functions.
8431 // Just don't report anything.
8432 if (Fn->isInvalidDecl() &&
8433 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo43847122013-07-19 23:00:19 +00008434 return true;
8435
8436 if (NumArgs < MinParams) {
8437 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8438 (Cand->FailureKind == ovl_fail_bad_deduction &&
8439 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8440 } else {
8441 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8442 (Cand->FailureKind == ovl_fail_bad_deduction &&
8443 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8444 }
8445
8446 return false;
8447}
8448
8449/// General arity mismatch diagnosis over a candidate in a candidate set.
8450void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
8451 assert(isa<FunctionDecl>(D) &&
8452 "The templated declaration should at least be a function"
8453 " when diagnosing bad template argument deduction due to too many"
8454 " or too few arguments");
8455
8456 FunctionDecl *Fn = cast<FunctionDecl>(D);
8457
8458 // TODO: treat calls to a missing default constructor as a special case
8459 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8460 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor439d3c32011-05-05 00:13:13 +00008461
John McCalladbb8f82010-01-13 09:16:55 +00008462 // at least / at most / exactly
8463 unsigned mode, modeCount;
8464 if (NumFormalArgs < MinParams) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008465 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00008466 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00008467 mode = 0; // "at least"
8468 else
8469 mode = 2; // "exactly"
8470 modeCount = MinParams;
8471 } else {
John McCalladbb8f82010-01-13 09:16:55 +00008472 if (MinParams != FnTy->getNumArgs())
8473 mode = 1; // "at most"
8474 else
8475 mode = 2; // "exactly"
8476 modeCount = FnTy->getNumArgs();
8477 }
8478
8479 std::string Description;
8480 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8481
Richard Smithf7b80562012-05-11 05:16:41 +00008482 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8483 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8484 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8485 << Fn->getParamDecl(0) << NumFormalArgs;
8486 else
8487 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8488 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8489 << modeCount << NumFormalArgs;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008490 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008491}
8492
Larisse Voufo43847122013-07-19 23:00:19 +00008493/// Arity mismatch diagnosis specific to a function overload candidate.
8494void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8495 unsigned NumFormalArgs) {
8496 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
8497 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
8498}
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008499
Larisse Voufo43847122013-07-19 23:00:19 +00008500TemplateDecl *getDescribedTemplate(Decl *Templated) {
8501 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
8502 return FD->getDescribedFunctionTemplate();
8503 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
8504 return RD->getDescribedClassTemplate();
8505
8506 llvm_unreachable("Unsupported: Getting the described template declaration"
8507 " for bad deduction diagnosis");
8508}
8509
8510/// Diagnose a failed template-argument deduction.
8511void DiagnoseBadDeduction(Sema &S, Decl *Templated,
8512 DeductionFailureInfo &DeductionFailure,
8513 unsigned NumArgs) {
8514 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00008515 NamedDecl *ParamD;
8516 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8517 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8518 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo43847122013-07-19 23:00:19 +00008519 switch (DeductionFailure.Result) {
John McCall342fec42010-02-01 18:53:26 +00008520 case Sema::TDK_Success:
8521 llvm_unreachable("TDK_success while diagnosing bad deduction");
8522
8523 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00008524 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo43847122013-07-19 23:00:19 +00008525 S.Diag(Templated->getLocation(),
8526 diag::note_ovl_candidate_incomplete_deduction)
8527 << ParamD->getDeclName();
8528 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall342fec42010-02-01 18:53:26 +00008529 return;
8530 }
8531
John McCall57e97782010-08-05 09:05:08 +00008532 case Sema::TDK_Underqualified: {
8533 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8534 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8535
Larisse Voufo43847122013-07-19 23:00:19 +00008536 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall57e97782010-08-05 09:05:08 +00008537
8538 // Param will have been canonicalized, but it should just be a
8539 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00008540 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00008541 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00008542 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00008543 assert(S.Context.hasSameType(Param, NonCanonParam));
8544
8545 // Arg has also been canonicalized, but there's nothing we can do
8546 // about that. It also doesn't matter as much, because it won't
8547 // have any template parameters in it (because deduction isn't
8548 // done on dependent types).
Larisse Voufo43847122013-07-19 23:00:19 +00008549 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall57e97782010-08-05 09:05:08 +00008550
Larisse Voufo43847122013-07-19 23:00:19 +00008551 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
8552 << ParamD->getDeclName() << Arg << NonCanonParam;
8553 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall57e97782010-08-05 09:05:08 +00008554 return;
8555 }
8556
8557 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00008558 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00008559 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008560 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008561 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008562 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008563 which = 1;
8564 else {
Douglas Gregora9333192010-05-08 17:41:32 +00008565 which = 2;
8566 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008567
Larisse Voufo43847122013-07-19 23:00:19 +00008568 S.Diag(Templated->getLocation(),
8569 diag::note_ovl_candidate_inconsistent_deduction)
8570 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
8571 << *DeductionFailure.getSecondArg();
8572 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregora9333192010-05-08 17:41:32 +00008573 return;
8574 }
Douglas Gregora18592e2010-05-08 18:13:28 +00008575
Douglas Gregorf1a84452010-05-08 19:15:54 +00008576 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008577 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregorf1a84452010-05-08 19:15:54 +00008578 if (ParamD->getDeclName())
Larisse Voufo43847122013-07-19 23:00:19 +00008579 S.Diag(Templated->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008580 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo43847122013-07-19 23:00:19 +00008581 << ParamD->getDeclName();
Douglas Gregorf1a84452010-05-08 19:15:54 +00008582 else {
8583 int index = 0;
8584 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8585 index = TTP->getIndex();
8586 else if (NonTypeTemplateParmDecl *NTTP
8587 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8588 index = NTTP->getIndex();
8589 else
8590 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo43847122013-07-19 23:00:19 +00008591 S.Diag(Templated->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008592 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo43847122013-07-19 23:00:19 +00008593 << (index + 1);
Douglas Gregorf1a84452010-05-08 19:15:54 +00008594 }
Larisse Voufo43847122013-07-19 23:00:19 +00008595 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregorf1a84452010-05-08 19:15:54 +00008596 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008597
Douglas Gregora18592e2010-05-08 18:13:28 +00008598 case Sema::TDK_TooManyArguments:
8599 case Sema::TDK_TooFewArguments:
Larisse Voufo43847122013-07-19 23:00:19 +00008600 DiagnoseArityMismatch(S, Templated, NumArgs);
Douglas Gregora18592e2010-05-08 18:13:28 +00008601 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00008602
8603 case Sema::TDK_InstantiationDepth:
Larisse Voufo43847122013-07-19 23:00:19 +00008604 S.Diag(Templated->getLocation(),
8605 diag::note_ovl_candidate_instantiation_depth);
8606 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregorec20f462010-05-08 20:07:26 +00008607 return;
8608
8609 case Sema::TDK_SubstitutionFailure: {
Richard Smithb8590f32012-05-07 09:03:25 +00008610 // Format the template argument list into the argument string.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008611 SmallString<128> TemplateArgString;
Richard Smithb8590f32012-05-07 09:03:25 +00008612 if (TemplateArgumentList *Args =
Larisse Voufo43847122013-07-19 23:00:19 +00008613 DeductionFailure.getTemplateArgumentList()) {
Richard Smithb8590f32012-05-07 09:03:25 +00008614 TemplateArgString = " ";
8615 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo43847122013-07-19 23:00:19 +00008616 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smithb8590f32012-05-07 09:03:25 +00008617 }
8618
Richard Smith4493c0a2012-05-09 05:17:00 +00008619 // If this candidate was disabled by enable_if, say so.
Larisse Voufo43847122013-07-19 23:00:19 +00008620 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith4493c0a2012-05-09 05:17:00 +00008621 if (PDiag && PDiag->second.getDiagID() ==
8622 diag::err_typename_nested_not_found_enable_if) {
8623 // FIXME: Use the source range of the condition, and the fully-qualified
8624 // name of the enable_if template. These are both present in PDiag.
8625 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8626 << "'enable_if'" << TemplateArgString;
8627 return;
8628 }
8629
Richard Smithb8590f32012-05-07 09:03:25 +00008630 // Format the SFINAE diagnostic into the argument string.
8631 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8632 // formatted message in another diagnostic.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008633 SmallString<128> SFINAEArgString;
Richard Smithb8590f32012-05-07 09:03:25 +00008634 SourceRange R;
Richard Smith4493c0a2012-05-09 05:17:00 +00008635 if (PDiag) {
Richard Smithb8590f32012-05-07 09:03:25 +00008636 SFINAEArgString = ": ";
8637 R = SourceRange(PDiag->first, PDiag->first);
8638 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8639 }
8640
Larisse Voufo43847122013-07-19 23:00:19 +00008641 S.Diag(Templated->getLocation(),
8642 diag::note_ovl_candidate_substitution_failure)
8643 << TemplateArgString << SFINAEArgString << R;
8644 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregorec20f462010-05-08 20:07:26 +00008645 return;
8646 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008647
Richard Smith0efa62f2013-01-31 04:03:12 +00008648 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo43847122013-07-19 23:00:19 +00008649 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
8650 S.Diag(Templated->getLocation(),
Richard Smith0efa62f2013-01-31 04:03:12 +00008651 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo43847122013-07-19 23:00:19 +00008652 << R.Expression->getName();
Richard Smith0efa62f2013-01-31 04:03:12 +00008653 return;
8654 }
8655
Richard Trieueef35f82013-04-08 21:11:40 +00008656 case Sema::TDK_NonDeducedMismatch: {
Richard Smith29805ca2013-01-31 05:19:49 +00008657 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo43847122013-07-19 23:00:19 +00008658 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
8659 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieueef35f82013-04-08 21:11:40 +00008660 if (FirstTA.getKind() == TemplateArgument::Template &&
8661 SecondTA.getKind() == TemplateArgument::Template) {
8662 TemplateName FirstTN = FirstTA.getAsTemplate();
8663 TemplateName SecondTN = SecondTA.getAsTemplate();
8664 if (FirstTN.getKind() == TemplateName::Template &&
8665 SecondTN.getKind() == TemplateName::Template) {
8666 if (FirstTN.getAsTemplateDecl()->getName() ==
8667 SecondTN.getAsTemplateDecl()->getName()) {
8668 // FIXME: This fixes a bad diagnostic where both templates are named
8669 // the same. This particular case is a bit difficult since:
8670 // 1) It is passed as a string to the diagnostic printer.
8671 // 2) The diagnostic printer only attempts to find a better
8672 // name for types, not decls.
8673 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo43847122013-07-19 23:00:19 +00008674 S.Diag(Templated->getLocation(),
Richard Trieueef35f82013-04-08 21:11:40 +00008675 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
8676 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
8677 return;
8678 }
8679 }
8680 }
Larisse Voufo43847122013-07-19 23:00:19 +00008681 S.Diag(Templated->getLocation(),
8682 diag::note_ovl_candidate_non_deduced_mismatch)
8683 << FirstTA << SecondTA;
Richard Smith29805ca2013-01-31 05:19:49 +00008684 return;
Richard Trieueef35f82013-04-08 21:11:40 +00008685 }
John McCall342fec42010-02-01 18:53:26 +00008686 // TODO: diagnose these individually, then kill off
8687 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith29805ca2013-01-31 05:19:49 +00008688 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo43847122013-07-19 23:00:19 +00008689 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
8690 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall342fec42010-02-01 18:53:26 +00008691 return;
8692 }
8693}
8694
Larisse Voufo43847122013-07-19 23:00:19 +00008695/// Diagnose a failed template-argument deduction, for function calls.
8696void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, unsigned NumArgs) {
8697 unsigned TDK = Cand->DeductionFailure.Result;
8698 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
8699 if (CheckArityMismatch(S, Cand, NumArgs))
8700 return;
8701 }
8702 DiagnoseBadDeduction(S, Cand->Function, // pattern
8703 Cand->DeductionFailure, NumArgs);
8704}
8705
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008706/// CUDA: diagnose an invalid call across targets.
8707void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8708 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8709 FunctionDecl *Callee = Cand->Function;
8710
8711 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8712 CalleeTarget = S.IdentifyCUDATarget(Callee);
8713
8714 std::string FnDesc;
8715 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8716
8717 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8718 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8719}
8720
John McCall342fec42010-02-01 18:53:26 +00008721/// Generates a 'note' diagnostic for an overload candidate. We've
8722/// already generated a primary error at the call site.
8723///
8724/// It really does need to be a single diagnostic with its caret
8725/// pointed at the candidate declaration. Yes, this creates some
8726/// major challenges of technical writing. Yes, this makes pointing
8727/// out problems with specific arguments quite awkward. It's still
8728/// better than generating twenty screens of text for every failed
8729/// overload.
8730///
8731/// It would be great to be able to express per-candidate problems
8732/// more richly for those diagnostic clients that cared, but we'd
8733/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00008734void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008735 unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00008736 FunctionDecl *Fn = Cand->Function;
8737
John McCall81201622010-01-08 04:41:39 +00008738 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008739 if (Cand->Viable && (Fn->isDeleted() ||
8740 S.isFunctionConsideredUnavailable(Fn))) {
John McCall220ccbf2010-01-13 00:25:19 +00008741 std::string FnDesc;
8742 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00008743
8744 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith5bdaac52012-04-02 20:59:25 +00008745 << FnKind << FnDesc
8746 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008747 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalla1d7d622010-01-08 00:58:21 +00008748 return;
John McCall81201622010-01-08 04:41:39 +00008749 }
8750
John McCall220ccbf2010-01-13 00:25:19 +00008751 // We don't really have anything else to say about viable candidates.
8752 if (Cand->Viable) {
8753 S.NoteOverloadCandidate(Fn);
8754 return;
8755 }
John McCall1d318332010-01-12 00:44:57 +00008756
John McCalladbb8f82010-01-13 09:16:55 +00008757 switch (Cand->FailureKind) {
8758 case ovl_fail_too_many_arguments:
8759 case ovl_fail_too_few_arguments:
8760 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00008761
John McCalladbb8f82010-01-13 09:16:55 +00008762 case ovl_fail_bad_deduction:
Ahmed Charles13a140c2012-02-25 11:00:22 +00008763 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall342fec42010-02-01 18:53:26 +00008764
John McCall717e8912010-01-23 05:17:32 +00008765 case ovl_fail_trivial_conversion:
8766 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00008767 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00008768 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008769
John McCallb1bdc622010-02-25 01:37:24 +00008770 case ovl_fail_bad_conversion: {
8771 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008772 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00008773 if (Cand->Conversions[I].isBad())
8774 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008775
John McCalladbb8f82010-01-13 09:16:55 +00008776 // FIXME: this currently happens when we're called from SemaInit
8777 // when user-conversion overload fails. Figure out how to handle
8778 // those conditions and diagnose them well.
8779 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008780 }
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008781
8782 case ovl_fail_bad_target:
8783 return DiagnoseBadTarget(S, Cand);
John McCallb1bdc622010-02-25 01:37:24 +00008784 }
John McCalla1d7d622010-01-08 00:58:21 +00008785}
8786
8787void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8788 // Desugar the type of the surrogate down to a function type,
8789 // retaining as many typedefs as possible while still showing
8790 // the function type (and, therefore, its parameter types).
8791 QualType FnType = Cand->Surrogate->getConversionType();
8792 bool isLValueReference = false;
8793 bool isRValueReference = false;
8794 bool isPointer = false;
8795 if (const LValueReferenceType *FnTypeRef =
8796 FnType->getAs<LValueReferenceType>()) {
8797 FnType = FnTypeRef->getPointeeType();
8798 isLValueReference = true;
8799 } else if (const RValueReferenceType *FnTypeRef =
8800 FnType->getAs<RValueReferenceType>()) {
8801 FnType = FnTypeRef->getPointeeType();
8802 isRValueReference = true;
8803 }
8804 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8805 FnType = FnTypePtr->getPointeeType();
8806 isPointer = true;
8807 }
8808 // Desugar down to a function type.
8809 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8810 // Reconstruct the pointer/reference as appropriate.
8811 if (isPointer) FnType = S.Context.getPointerType(FnType);
8812 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8813 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8814
8815 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8816 << FnType;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008817 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalla1d7d622010-01-08 00:58:21 +00008818}
8819
8820void NoteBuiltinOperatorCandidate(Sema &S,
David Blaikie0bea8632012-10-08 01:11:04 +00008821 StringRef Opc,
John McCalla1d7d622010-01-08 00:58:21 +00008822 SourceLocation OpLoc,
8823 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008824 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalla1d7d622010-01-08 00:58:21 +00008825 std::string TypeStr("operator");
8826 TypeStr += Opc;
8827 TypeStr += "(";
8828 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008829 if (Cand->NumConversions == 1) {
John McCalla1d7d622010-01-08 00:58:21 +00008830 TypeStr += ")";
8831 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8832 } else {
8833 TypeStr += ", ";
8834 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8835 TypeStr += ")";
8836 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8837 }
8838}
8839
8840void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8841 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008842 unsigned NoOperands = Cand->NumConversions;
John McCalla1d7d622010-01-08 00:58:21 +00008843 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8844 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00008845 if (ICS.isBad()) break; // all meaningless after first invalid
8846 if (!ICS.isAmbiguous()) continue;
8847
John McCall120d63c2010-08-24 20:38:10 +00008848 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008849 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00008850 }
8851}
8852
Larisse Voufo43847122013-07-19 23:00:19 +00008853static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall1b77e732010-01-15 23:32:50 +00008854 if (Cand->Function)
8855 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00008856 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00008857 return Cand->Surrogate->getLocation();
8858 return SourceLocation();
8859}
8860
Larisse Voufo43847122013-07-19 23:00:19 +00008861static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth78bf6802011-09-10 00:51:24 +00008862 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008863 case Sema::TDK_Success:
David Blaikieb219cfc2011-09-23 05:06:16 +00008864 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008865
Douglas Gregorae19fbb2012-09-13 21:01:57 +00008866 case Sema::TDK_Invalid:
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008867 case Sema::TDK_Incomplete:
8868 return 1;
8869
8870 case Sema::TDK_Underqualified:
8871 case Sema::TDK_Inconsistent:
8872 return 2;
8873
8874 case Sema::TDK_SubstitutionFailure:
8875 case Sema::TDK_NonDeducedMismatch:
Richard Smith29805ca2013-01-31 05:19:49 +00008876 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008877 return 3;
8878
8879 case Sema::TDK_InstantiationDepth:
8880 case Sema::TDK_FailedOverloadResolution:
8881 return 4;
8882
8883 case Sema::TDK_InvalidExplicitArguments:
8884 return 5;
8885
8886 case Sema::TDK_TooManyArguments:
8887 case Sema::TDK_TooFewArguments:
8888 return 6;
8889 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008890 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008891}
8892
John McCallbf65c0b2010-01-12 00:48:53 +00008893struct CompareOverloadCandidatesForDisplay {
8894 Sema &S;
8895 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00008896
8897 bool operator()(const OverloadCandidate *L,
8898 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00008899 // Fast-path this check.
8900 if (L == R) return false;
8901
John McCall81201622010-01-08 04:41:39 +00008902 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00008903 if (L->Viable) {
8904 if (!R->Viable) return true;
8905
8906 // TODO: introduce a tri-valued comparison for overload
8907 // candidates. Would be more worthwhile if we had a sort
8908 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00008909 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8910 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00008911 } else if (R->Viable)
8912 return false;
John McCall81201622010-01-08 04:41:39 +00008913
John McCall1b77e732010-01-15 23:32:50 +00008914 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00008915
John McCall1b77e732010-01-15 23:32:50 +00008916 // Criteria by which we can sort non-viable candidates:
8917 if (!L->Viable) {
8918 // 1. Arity mismatches come after other candidates.
8919 if (L->FailureKind == ovl_fail_too_many_arguments ||
8920 L->FailureKind == ovl_fail_too_few_arguments)
8921 return false;
8922 if (R->FailureKind == ovl_fail_too_many_arguments ||
8923 R->FailureKind == ovl_fail_too_few_arguments)
8924 return true;
John McCall81201622010-01-08 04:41:39 +00008925
John McCall717e8912010-01-23 05:17:32 +00008926 // 2. Bad conversions come first and are ordered by the number
8927 // of bad conversions and quality of good conversions.
8928 if (L->FailureKind == ovl_fail_bad_conversion) {
8929 if (R->FailureKind != ovl_fail_bad_conversion)
8930 return true;
8931
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008932 // The conversion that can be fixed with a smaller number of changes,
8933 // comes first.
8934 unsigned numLFixes = L->Fix.NumConversionsFixed;
8935 unsigned numRFixes = R->Fix.NumConversionsFixed;
8936 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8937 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008938 if (numLFixes != numRFixes) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008939 if (numLFixes < numRFixes)
8940 return true;
8941 else
8942 return false;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008943 }
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008944
John McCall717e8912010-01-23 05:17:32 +00008945 // If there's any ordering between the defined conversions...
8946 // FIXME: this might not be transitive.
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008947 assert(L->NumConversions == R->NumConversions);
John McCall717e8912010-01-23 05:17:32 +00008948
8949 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00008950 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008951 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00008952 switch (CompareImplicitConversionSequences(S,
8953 L->Conversions[I],
8954 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00008955 case ImplicitConversionSequence::Better:
8956 leftBetter++;
8957 break;
8958
8959 case ImplicitConversionSequence::Worse:
8960 leftBetter--;
8961 break;
8962
8963 case ImplicitConversionSequence::Indistinguishable:
8964 break;
8965 }
8966 }
8967 if (leftBetter > 0) return true;
8968 if (leftBetter < 0) return false;
8969
8970 } else if (R->FailureKind == ovl_fail_bad_conversion)
8971 return false;
8972
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008973 if (L->FailureKind == ovl_fail_bad_deduction) {
8974 if (R->FailureKind != ovl_fail_bad_deduction)
8975 return true;
8976
8977 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8978 return RankDeductionFailure(L->DeductionFailure)
Eli Friedmance1846e2011-10-14 23:10:30 +00008979 < RankDeductionFailure(R->DeductionFailure);
Eli Friedman1c522f72011-10-14 21:52:24 +00008980 } else if (R->FailureKind == ovl_fail_bad_deduction)
8981 return false;
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008982
John McCall1b77e732010-01-15 23:32:50 +00008983 // TODO: others?
8984 }
8985
8986 // Sort everything else by location.
8987 SourceLocation LLoc = GetLocationForCandidate(L);
8988 SourceLocation RLoc = GetLocationForCandidate(R);
8989
8990 // Put candidates without locations (e.g. builtins) at the end.
8991 if (LLoc.isInvalid()) return false;
8992 if (RLoc.isInvalid()) return true;
8993
8994 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00008995 }
8996};
8997
John McCall717e8912010-01-23 05:17:32 +00008998/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008999/// computes up to the first. Produces the FixIt set if possible.
John McCall717e8912010-01-23 05:17:32 +00009000void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009001 ArrayRef<Expr *> Args) {
John McCall717e8912010-01-23 05:17:32 +00009002 assert(!Cand->Viable);
9003
9004 // Don't do anything on failures other than bad conversion.
9005 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9006
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009007 // We only want the FixIts if all the arguments can be corrected.
9008 bool Unfixable = false;
Anna Zaksf3546ee2011-07-28 19:46:48 +00009009 // Use a implicit copy initialization to check conversion fixes.
9010 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009011
John McCall717e8912010-01-23 05:17:32 +00009012 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00009013 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00009014 unsigned ConvCount = Cand->NumConversions;
John McCall717e8912010-01-23 05:17:32 +00009015 while (true) {
9016 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9017 ConvIdx++;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009018 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaksf3546ee2011-07-28 19:46:48 +00009019 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCall717e8912010-01-23 05:17:32 +00009020 break;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009021 }
John McCall717e8912010-01-23 05:17:32 +00009022 }
9023
9024 if (ConvIdx == ConvCount)
9025 return;
9026
John McCallb1bdc622010-02-25 01:37:24 +00009027 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9028 "remaining conversion is initialized?");
9029
Douglas Gregor23ef6c02010-04-16 17:45:54 +00009030 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00009031 // operation somehow.
9032 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00009033
9034 const FunctionProtoType* Proto;
9035 unsigned ArgIdx = ConvIdx;
9036
9037 if (Cand->IsSurrogate) {
9038 QualType ConvType
9039 = Cand->Surrogate->getConversionType().getNonReferenceType();
9040 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9041 ConvType = ConvPtrType->getPointeeType();
9042 Proto = ConvType->getAs<FunctionProtoType>();
9043 ArgIdx--;
9044 } else if (Cand->Function) {
9045 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9046 if (isa<CXXMethodDecl>(Cand->Function) &&
9047 !isa<CXXConstructorDecl>(Cand->Function))
9048 ArgIdx--;
9049 } else {
9050 // Builtin binary operator with a bad first conversion.
9051 assert(ConvCount <= 3);
9052 for (; ConvIdx != ConvCount; ++ConvIdx)
9053 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00009054 = TryCopyInitialization(S, Args[ConvIdx],
9055 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009056 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00009057 /*InOverloadResolution*/ true,
9058 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00009059 S.getLangOpts().ObjCAutoRefCount);
John McCall717e8912010-01-23 05:17:32 +00009060 return;
9061 }
9062
9063 // Fill in the rest of the conversions.
9064 unsigned NumArgsInProto = Proto->getNumArgs();
9065 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009066 if (ArgIdx < NumArgsInProto) {
John McCall717e8912010-01-23 05:17:32 +00009067 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00009068 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009069 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00009070 /*InOverloadResolution=*/true,
9071 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00009072 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009073 // Store the FixIt in the candidate if it exists.
9074 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaksf3546ee2011-07-28 19:46:48 +00009075 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009076 }
John McCall717e8912010-01-23 05:17:32 +00009077 else
9078 Cand->Conversions[ConvIdx].setEllipsis();
9079 }
9080}
9081
John McCalla1d7d622010-01-08 00:58:21 +00009082} // end anonymous namespace
9083
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00009084/// PrintOverloadCandidates - When overload resolution fails, prints
9085/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00009086/// set.
John McCall120d63c2010-08-24 20:38:10 +00009087void OverloadCandidateSet::NoteCandidates(Sema &S,
9088 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009089 ArrayRef<Expr *> Args,
David Blaikie0bea8632012-10-08 01:11:04 +00009090 StringRef Opc,
John McCall120d63c2010-08-24 20:38:10 +00009091 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00009092 // Sort the candidates by viability and position. Sorting directly would
9093 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00009094 SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00009095 if (OCD == OCD_AllCandidates) Cands.reserve(size());
9096 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00009097 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00009098 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00009099 else if (OCD == OCD_AllCandidates) {
Ahmed Charles13a140c2012-02-25 11:00:22 +00009100 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009101 if (Cand->Function || Cand->IsSurrogate)
9102 Cands.push_back(Cand);
9103 // Otherwise, this a non-viable builtin candidate. We do not, in general,
9104 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00009105 }
9106 }
9107
John McCallbf65c0b2010-01-12 00:48:53 +00009108 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00009109 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009110
John McCall1d318332010-01-12 00:44:57 +00009111 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00009112
Chris Lattner5f9e2722011-07-23 10:55:15 +00009113 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregordc7b6412012-10-23 23:11:23 +00009114 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009115 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00009116 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9117 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00009118
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009119 // Set an arbitrary limit on the number of candidate functions we'll spam
9120 // the user with. FIXME: This limit should depend on details of the
9121 // candidate list.
Douglas Gregordc7b6412012-10-23 23:11:23 +00009122 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009123 break;
9124 }
9125 ++CandsShown;
9126
John McCalla1d7d622010-01-08 00:58:21 +00009127 if (Cand->Function)
Ahmed Charles13a140c2012-02-25 11:00:22 +00009128 NoteFunctionCandidate(S, Cand, Args.size());
John McCalla1d7d622010-01-08 00:58:21 +00009129 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00009130 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009131 else {
9132 assert(Cand->Viable &&
9133 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00009134 // Generally we only see ambiguities including viable builtin
9135 // operators if overload resolution got screwed up by an
9136 // ambiguous user-defined conversion.
9137 //
9138 // FIXME: It's quite possible for different conversions to see
9139 // different ambiguities, though.
9140 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00009141 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00009142 ReportedAmbiguousConversions = true;
9143 }
John McCalla1d7d622010-01-08 00:58:21 +00009144
John McCall1d318332010-01-12 00:44:57 +00009145 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00009146 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00009147 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00009148 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009149
9150 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00009151 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00009152}
9153
Larisse Voufo43847122013-07-19 23:00:19 +00009154static SourceLocation
9155GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9156 return Cand->Specialization ? Cand->Specialization->getLocation()
9157 : SourceLocation();
9158}
9159
9160struct CompareTemplateSpecCandidatesForDisplay {
9161 Sema &S;
9162 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9163
9164 bool operator()(const TemplateSpecCandidate *L,
9165 const TemplateSpecCandidate *R) {
9166 // Fast-path this check.
9167 if (L == R)
9168 return false;
9169
9170 // Assuming that both candidates are not matches...
9171
9172 // Sort by the ranking of deduction failures.
9173 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9174 return RankDeductionFailure(L->DeductionFailure) <
9175 RankDeductionFailure(R->DeductionFailure);
9176
9177 // Sort everything else by location.
9178 SourceLocation LLoc = GetLocationForCandidate(L);
9179 SourceLocation RLoc = GetLocationForCandidate(R);
9180
9181 // Put candidates without locations (e.g. builtins) at the end.
9182 if (LLoc.isInvalid())
9183 return false;
9184 if (RLoc.isInvalid())
9185 return true;
9186
9187 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9188 }
9189};
9190
9191/// Diagnose a template argument deduction failure.
9192/// We are treating these failures as overload failures due to bad
9193/// deductions.
9194void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9195 DiagnoseBadDeduction(S, Specialization, // pattern
9196 DeductionFailure, /*NumArgs=*/0);
9197}
9198
9199void TemplateSpecCandidateSet::destroyCandidates() {
9200 for (iterator i = begin(), e = end(); i != e; ++i) {
9201 i->DeductionFailure.Destroy();
9202 }
9203}
9204
9205void TemplateSpecCandidateSet::clear() {
9206 destroyCandidates();
9207 Candidates.clear();
9208}
9209
9210/// NoteCandidates - When no template specialization match is found, prints
9211/// diagnostic messages containing the non-matching specializations that form
9212/// the candidate set.
9213/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9214/// OCD == OCD_AllCandidates and Cand->Viable == false.
9215void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9216 // Sort the candidates by position (assuming no candidate is a match).
9217 // Sorting directly would be prohibitive, so we make a set of pointers
9218 // and sort those.
9219 SmallVector<TemplateSpecCandidate *, 32> Cands;
9220 Cands.reserve(size());
9221 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9222 if (Cand->Specialization)
9223 Cands.push_back(Cand);
9224 // Otherwise, this is a non matching builtin candidate. We do not,
9225 // in general, want to list every possible builtin candidate.
9226 }
9227
9228 std::sort(Cands.begin(), Cands.end(),
9229 CompareTemplateSpecCandidatesForDisplay(S));
9230
9231 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9232 // for generalization purposes (?).
9233 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9234
9235 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9236 unsigned CandsShown = 0;
9237 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9238 TemplateSpecCandidate *Cand = *I;
9239
9240 // Set an arbitrary limit on the number of candidates we'll spam
9241 // the user with. FIXME: This limit should depend on details of the
9242 // candidate list.
9243 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9244 break;
9245 ++CandsShown;
9246
9247 assert(Cand->Specialization &&
9248 "Non-matching built-in candidates are not added to Cands.");
9249 Cand->NoteDeductionFailure(S);
9250 }
9251
9252 if (I != E)
9253 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9254}
9255
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009256// [PossiblyAFunctionType] --> [Return]
9257// NonFunctionType --> NonFunctionType
9258// R (A) --> R(A)
9259// R (*)(A) --> R (A)
9260// R (&)(A) --> R (A)
9261// R (S::*)(A) --> R (A)
9262QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9263 QualType Ret = PossiblyAFunctionType;
9264 if (const PointerType *ToTypePtr =
9265 PossiblyAFunctionType->getAs<PointerType>())
9266 Ret = ToTypePtr->getPointeeType();
9267 else if (const ReferenceType *ToTypeRef =
9268 PossiblyAFunctionType->getAs<ReferenceType>())
9269 Ret = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00009270 else if (const MemberPointerType *MemTypePtr =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009271 PossiblyAFunctionType->getAs<MemberPointerType>())
9272 Ret = MemTypePtr->getPointeeType();
9273 Ret =
9274 Context.getCanonicalType(Ret).getUnqualifiedType();
9275 return Ret;
9276}
Douglas Gregor904eed32008-11-10 20:40:00 +00009277
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009278// A helper class to help with address of function resolution
9279// - allows us to avoid passing around all those ugly parameters
9280class AddressOfFunctionResolver
9281{
9282 Sema& S;
9283 Expr* SourceExpr;
9284 const QualType& TargetType;
9285 QualType TargetFunctionType; // Extracted function type from target type
9286
9287 bool Complain;
9288 //DeclAccessPair& ResultFunctionAccessPair;
9289 ASTContext& Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009290
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009291 bool TargetTypeIsNonStaticMemberFunction;
9292 bool FoundNonTemplateFunction;
David Majnemer576a9af2013-08-01 06:13:59 +00009293 bool StaticMemberFunctionFromBoundPointer;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009294
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009295 OverloadExpr::FindResult OvlExprInfo;
9296 OverloadExpr *OvlExpr;
9297 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009298 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo43847122013-07-19 23:00:19 +00009299 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009300
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009301public:
Larisse Voufo43847122013-07-19 23:00:19 +00009302 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9303 const QualType &TargetType, bool Complain)
9304 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9305 Complain(Complain), Context(S.getASTContext()),
9306 TargetTypeIsNonStaticMemberFunction(
9307 !!TargetType->getAs<MemberPointerType>()),
9308 FoundNonTemplateFunction(false),
David Majnemer576a9af2013-08-01 06:13:59 +00009309 StaticMemberFunctionFromBoundPointer(false),
Larisse Voufo43847122013-07-19 23:00:19 +00009310 OvlExprInfo(OverloadExpr::find(SourceExpr)),
9311 OvlExpr(OvlExprInfo.Expression),
9312 FailedCandidates(OvlExpr->getNameLoc()) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009313 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruth90434232011-03-29 08:08:18 +00009314
David Majnemer576a9af2013-08-01 06:13:59 +00009315 if (TargetFunctionType->isFunctionType()) {
9316 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9317 if (!UME->isImplicitAccess() &&
9318 !S.ResolveSingleFunctionTemplateSpecialization(UME))
9319 StaticMemberFunctionFromBoundPointer = true;
9320 } else if (OvlExpr->hasExplicitTemplateArgs()) {
9321 DeclAccessPair dap;
9322 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9323 OvlExpr, false, &dap)) {
9324 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9325 if (!Method->isStatic()) {
9326 // If the target type is a non-function type and the function found
9327 // is a non-static member function, pretend as if that was the
9328 // target, it's the only possible type to end up with.
9329 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruth90434232011-03-29 08:08:18 +00009330
David Majnemer576a9af2013-08-01 06:13:59 +00009331 // And skip adding the function if its not in the proper form.
9332 // We'll diagnose this due to an empty set of functions.
9333 if (!OvlExprInfo.HasFormOfMemberPointer)
9334 return;
Chandler Carruth90434232011-03-29 08:08:18 +00009335 }
9336
David Majnemer576a9af2013-08-01 06:13:59 +00009337 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor83314aa2009-07-08 20:55:45 +00009338 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009339 return;
Douglas Gregor83314aa2009-07-08 20:55:45 +00009340 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009341
9342 if (OvlExpr->hasExplicitTemplateArgs())
9343 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00009344
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009345 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9346 // C++ [over.over]p4:
9347 // If more than one function is selected, [...]
9348 if (Matches.size() > 1) {
9349 if (FoundNonTemplateFunction)
9350 EliminateAllTemplateMatches();
9351 else
9352 EliminateAllExceptMostSpecializedTemplate();
9353 }
9354 }
9355 }
9356
9357private:
9358 bool isTargetTypeAFunction() const {
9359 return TargetFunctionType->isFunctionType();
9360 }
9361
9362 // [ToType] [Return]
9363
9364 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9365 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9366 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9367 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9368 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9369 }
9370
9371 // return true if any matching specializations were found
9372 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9373 const DeclAccessPair& CurAccessFunPair) {
9374 if (CXXMethodDecl *Method
9375 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9376 // Skip non-static function templates when converting to pointer, and
9377 // static when converting to member pointer.
9378 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9379 return false;
9380 }
9381 else if (TargetTypeIsNonStaticMemberFunction)
9382 return false;
9383
9384 // C++ [over.over]p2:
9385 // If the name is a function template, template argument deduction is
9386 // done (14.8.2.2), and if the argument deduction succeeds, the
9387 // resulting template argument list is used to generate a single
9388 // function template specialization, which is added to the set of
9389 // overloaded functions considered.
9390 FunctionDecl *Specialization = 0;
Larisse Voufo43847122013-07-19 23:00:19 +00009391 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009392 if (Sema::TemplateDeductionResult Result
9393 = S.DeduceTemplateArguments(FunctionTemplate,
9394 &OvlExplicitTemplateArgs,
9395 TargetFunctionType, Specialization,
Douglas Gregor092140a2013-04-17 08:45:07 +00009396 Info, /*InOverloadResolution=*/true)) {
Larisse Voufo43847122013-07-19 23:00:19 +00009397 // Make a note of the failed deduction for diagnostics.
9398 FailedCandidates.addCandidate()
9399 .set(FunctionTemplate->getTemplatedDecl(),
9400 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009401 (void)Result;
9402 return false;
9403 }
9404
Douglas Gregor092140a2013-04-17 08:45:07 +00009405 // Template argument deduction ensures that we have an exact match or
9406 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009407 // This function template specicalization works.
9408 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Douglas Gregor092140a2013-04-17 08:45:07 +00009409 assert(S.isSameOrCompatibleFunctionType(
9410 Context.getCanonicalType(Specialization->getType()),
9411 Context.getCanonicalType(TargetFunctionType)));
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009412 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9413 return true;
9414 }
9415
9416 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9417 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthbd647292009-12-29 06:17:27 +00009418 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00009419 // Skip non-static functions when converting to pointer, and static
9420 // when converting to member pointer.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009421 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9422 return false;
9423 }
9424 else if (TargetTypeIsNonStaticMemberFunction)
9425 return false;
Douglas Gregor904eed32008-11-10 20:40:00 +00009426
Chandler Carruthbd647292009-12-29 06:17:27 +00009427 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009428 if (S.getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00009429 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9430 if (S.CheckCUDATarget(Caller, FunDecl))
9431 return false;
9432
Richard Smith60e141e2013-05-04 07:00:32 +00009433 // If any candidate has a placeholder return type, trigger its deduction
9434 // now.
9435 if (S.getLangOpts().CPlusPlus1y &&
9436 FunDecl->getResultType()->isUndeducedType() &&
9437 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
9438 return false;
9439
Douglas Gregor43c79c22009-12-09 00:47:37 +00009440 QualType ResultTy;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009441 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9442 FunDecl->getType()) ||
Chandler Carruth18e04612011-06-18 01:19:03 +00009443 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9444 ResultTy)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009445 Matches.push_back(std::make_pair(CurAccessFunPair,
9446 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00009447 FoundNonTemplateFunction = true;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009448 return true;
Douglas Gregor00aeb522009-07-08 23:33:52 +00009449 }
Mike Stump1eb44332009-09-09 15:08:12 +00009450 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009451
9452 return false;
9453 }
9454
9455 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9456 bool Ret = false;
9457
9458 // If the overload expression doesn't have the form of a pointer to
9459 // member, don't try to convert it to a pointer-to-member type.
9460 if (IsInvalidFormOfPointerToMemberFunction())
9461 return false;
9462
9463 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9464 E = OvlExpr->decls_end();
9465 I != E; ++I) {
9466 // Look through any using declarations to find the underlying function.
9467 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9468
9469 // C++ [over.over]p3:
9470 // Non-member functions and static member functions match
9471 // targets of type "pointer-to-function" or "reference-to-function."
9472 // Nonstatic member functions match targets of
9473 // type "pointer-to-member-function."
9474 // Note that according to DR 247, the containing class does not matter.
9475 if (FunctionTemplateDecl *FunctionTemplate
9476 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9477 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9478 Ret = true;
9479 }
9480 // If we have explicit template arguments supplied, skip non-templates.
9481 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9482 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9483 Ret = true;
9484 }
9485 assert(Ret || Matches.empty());
9486 return Ret;
Douglas Gregor904eed32008-11-10 20:40:00 +00009487 }
9488
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009489 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00009490 // [...] and any given function template specialization F1 is
9491 // eliminated if the set contains a second function template
9492 // specialization whose function template is more specialized
9493 // than the function template of F1 according to the partial
9494 // ordering rules of 14.5.5.2.
9495
9496 // The algorithm specified above is quadratic. We instead use a
9497 // two-pass algorithm (similar to the one used to identify the
9498 // best viable function in an overload set) that identifies the
9499 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00009500
9501 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9502 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9503 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009504
Larisse Voufo43847122013-07-19 23:00:19 +00009505 // TODO: It looks like FailedCandidates does not serve much purpose
9506 // here, since the no_viable diagnostic has index 0.
9507 UnresolvedSetIterator Result = S.getMostSpecialized(
9508 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, TPOC_Other, 0,
9509 SourceExpr->getLocStart(), S.PDiag(),
9510 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
9511 .second->getDeclName(),
9512 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
9513 Complain, TargetFunctionType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009514
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009515 if (Result != MatchesCopy.end()) {
9516 // Make it the first and only element
9517 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9518 Matches[0].second = cast<FunctionDecl>(*Result);
9519 Matches.resize(1);
John McCallc373d482010-01-27 01:50:18 +00009520 }
9521 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009522
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009523 void EliminateAllTemplateMatches() {
9524 // [...] any function template specializations in the set are
9525 // eliminated if the set also contains a non-template function, [...]
9526 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9527 if (Matches[I].second->getPrimaryTemplate() == 0)
9528 ++I;
9529 else {
9530 Matches[I] = Matches[--N];
9531 Matches.set_size(N);
9532 }
9533 }
9534 }
9535
9536public:
9537 void ComplainNoMatchesFound() const {
9538 assert(Matches.empty());
9539 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9540 << OvlExpr->getName() << TargetFunctionType
9541 << OvlExpr->getSourceRange();
Larisse Voufo43847122013-07-19 23:00:19 +00009542 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
Richard Trieu6efd4c52011-11-23 22:32:32 +00009543 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009544 }
9545
9546 bool IsInvalidFormOfPointerToMemberFunction() const {
9547 return TargetTypeIsNonStaticMemberFunction &&
9548 !OvlExprInfo.HasFormOfMemberPointer;
9549 }
David Majnemer576a9af2013-08-01 06:13:59 +00009550
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009551 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9552 // TODO: Should we condition this on whether any functions might
9553 // have matched, or is it more appropriate to do that in callers?
9554 // TODO: a fixit wouldn't hurt.
9555 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9556 << TargetType << OvlExpr->getSourceRange();
9557 }
David Majnemer576a9af2013-08-01 06:13:59 +00009558
9559 bool IsStaticMemberFunctionFromBoundPointer() const {
9560 return StaticMemberFunctionFromBoundPointer;
9561 }
9562
9563 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
9564 S.Diag(OvlExpr->getLocStart(),
9565 diag::err_invalid_form_pointer_member_function)
9566 << OvlExpr->getSourceRange();
9567 }
9568
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009569 void ComplainOfInvalidConversion() const {
9570 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9571 << OvlExpr->getName() << TargetType;
9572 }
9573
9574 void ComplainMultipleMatchesFound() const {
9575 assert(Matches.size() > 1);
9576 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9577 << OvlExpr->getName()
9578 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009579 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009580 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009581
9582 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9583
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009584 int getNumMatches() const { return Matches.size(); }
9585
9586 FunctionDecl* getMatchingFunctionDecl() const {
9587 if (Matches.size() != 1) return 0;
9588 return Matches[0].second;
9589 }
9590
9591 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9592 if (Matches.size() != 1) return 0;
9593 return &Matches[0].first;
9594 }
9595};
9596
9597/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9598/// an overloaded function (C++ [over.over]), where @p From is an
9599/// expression with overloaded function type and @p ToType is the type
9600/// we're trying to resolve to. For example:
9601///
9602/// @code
9603/// int f(double);
9604/// int f(int);
9605///
9606/// int (*pfd)(double) = f; // selects f(double)
9607/// @endcode
9608///
9609/// This routine returns the resulting FunctionDecl if it could be
9610/// resolved, and NULL otherwise. When @p Complain is true, this
9611/// routine will emit diagnostics if there is an error.
9612FunctionDecl *
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009613Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9614 QualType TargetType,
9615 bool Complain,
9616 DeclAccessPair &FoundResult,
9617 bool *pHadMultipleCandidates) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009618 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009619
9620 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9621 Complain);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009622 int NumMatches = Resolver.getNumMatches();
9623 FunctionDecl* Fn = 0;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009624 if (NumMatches == 0 && Complain) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009625 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9626 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9627 else
9628 Resolver.ComplainNoMatchesFound();
9629 }
9630 else if (NumMatches > 1 && Complain)
9631 Resolver.ComplainMultipleMatchesFound();
9632 else if (NumMatches == 1) {
9633 Fn = Resolver.getMatchingFunctionDecl();
9634 assert(Fn);
9635 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemer576a9af2013-08-01 06:13:59 +00009636 if (Complain) {
9637 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
9638 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
9639 else
9640 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
9641 }
Sebastian Redl07ab2022009-10-17 21:12:09 +00009642 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009643
9644 if (pHadMultipleCandidates)
9645 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009646 return Fn;
Douglas Gregor904eed32008-11-10 20:40:00 +00009647}
9648
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009649/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor4b52e252009-12-21 23:17:24 +00009650/// resolve that overloaded function expression down to a single function.
9651///
9652/// This routine can only resolve template-ids that refer to a single function
9653/// template, where that template-id refers to a single template whose template
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009654/// arguments are either provided by the template-id or have defaults,
Douglas Gregor4b52e252009-12-21 23:17:24 +00009655/// as described in C++0x [temp.arg.explicit]p3.
John McCall864c0412011-04-26 20:42:42 +00009656FunctionDecl *
9657Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9658 bool Complain,
9659 DeclAccessPair *FoundResult) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009660 // C++ [over.over]p1:
9661 // [...] [Note: any redundant set of parentheses surrounding the
9662 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00009663 // C++ [over.over]p1:
9664 // [...] The overloaded function name can be preceded by the &
9665 // operator.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009666
Douglas Gregor4b52e252009-12-21 23:17:24 +00009667 // If we didn't actually find any template-ids, we're done.
John McCall864c0412011-04-26 20:42:42 +00009668 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00009669 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00009670
9671 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall864c0412011-04-26 20:42:42 +00009672 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Larisse Voufo43847122013-07-19 23:00:19 +00009673 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009674
Douglas Gregor4b52e252009-12-21 23:17:24 +00009675 // Look through all of the overloaded functions, searching for one
9676 // whose type matches exactly.
9677 FunctionDecl *Matched = 0;
John McCall864c0412011-04-26 20:42:42 +00009678 for (UnresolvedSetIterator I = ovl->decls_begin(),
9679 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009680 // C++0x [temp.arg.explicit]p3:
9681 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009682 // where deduction is not done, if a template argument list is
9683 // specified and it, along with any default template arguments,
9684 // identifies a single function template specialization, then the
Douglas Gregor4b52e252009-12-21 23:17:24 +00009685 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00009686 FunctionTemplateDecl *FunctionTemplate
9687 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009688
Douglas Gregor4b52e252009-12-21 23:17:24 +00009689 // C++ [over.over]p2:
9690 // If the name is a function template, template argument deduction is
9691 // done (14.8.2.2), and if the argument deduction succeeds, the
9692 // resulting template argument list is used to generate a single
9693 // function template specialization, which is added to the set of
9694 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00009695 FunctionDecl *Specialization = 0;
Larisse Voufo43847122013-07-19 23:00:19 +00009696 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor4b52e252009-12-21 23:17:24 +00009697 if (TemplateDeductionResult Result
9698 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor092140a2013-04-17 08:45:07 +00009699 Specialization, Info,
9700 /*InOverloadResolution=*/true)) {
Larisse Voufo43847122013-07-19 23:00:19 +00009701 // Make a note of the failed deduction for diagnostics.
9702 // TODO: Actually use the failed-deduction info?
9703 FailedCandidates.addCandidate()
9704 .set(FunctionTemplate->getTemplatedDecl(),
9705 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor4b52e252009-12-21 23:17:24 +00009706 (void)Result;
9707 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009708 }
9709
John McCall864c0412011-04-26 20:42:42 +00009710 assert(Specialization && "no specialization and no error?");
9711
Douglas Gregor4b52e252009-12-21 23:17:24 +00009712 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009713 if (Matched) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009714 if (Complain) {
John McCall864c0412011-04-26 20:42:42 +00009715 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9716 << ovl->getName();
9717 NoteAllOverloadCandidates(ovl);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009718 }
Douglas Gregor4b52e252009-12-21 23:17:24 +00009719 return 0;
John McCall864c0412011-04-26 20:42:42 +00009720 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009721
John McCall864c0412011-04-26 20:42:42 +00009722 Matched = Specialization;
9723 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor4b52e252009-12-21 23:17:24 +00009724 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009725
Richard Smith60e141e2013-05-04 07:00:32 +00009726 if (Matched && getLangOpts().CPlusPlus1y &&
9727 Matched->getResultType()->isUndeducedType() &&
9728 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
9729 return 0;
9730
Douglas Gregor4b52e252009-12-21 23:17:24 +00009731 return Matched;
9732}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009733
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009734
9735
9736
John McCall6dbba4f2011-10-11 23:14:30 +00009737// Resolve and fix an overloaded expression that can be resolved
9738// because it identifies a single function template specialization.
9739//
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009740// Last three arguments should only be supplied if Complain = true
John McCall6dbba4f2011-10-11 23:14:30 +00009741//
9742// Return true if it was logically possible to so resolve the
9743// expression, regardless of whether or not it succeeded. Always
9744// returns true if 'complain' is set.
9745bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9746 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9747 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009748 QualType DestTypeForComplaining,
John McCall864c0412011-04-26 20:42:42 +00009749 unsigned DiagIDForComplaining) {
John McCall6dbba4f2011-10-11 23:14:30 +00009750 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009751
John McCall6dbba4f2011-10-11 23:14:30 +00009752 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009753
John McCall864c0412011-04-26 20:42:42 +00009754 DeclAccessPair found;
9755 ExprResult SingleFunctionExpression;
9756 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9757 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009758 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall6dbba4f2011-10-11 23:14:30 +00009759 SrcExpr = ExprError();
9760 return true;
9761 }
John McCall864c0412011-04-26 20:42:42 +00009762
9763 // It is only correct to resolve to an instance method if we're
9764 // resolving a form that's permitted to be a pointer to member.
9765 // Otherwise we'll end up making a bound member expression, which
9766 // is illegal in all the contexts we resolve like this.
9767 if (!ovl.HasFormOfMemberPointer &&
9768 isa<CXXMethodDecl>(fn) &&
9769 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall6dbba4f2011-10-11 23:14:30 +00009770 if (!complain) return false;
9771
9772 Diag(ovl.Expression->getExprLoc(),
9773 diag::err_bound_member_function)
9774 << 0 << ovl.Expression->getSourceRange();
9775
9776 // TODO: I believe we only end up here if there's a mix of
9777 // static and non-static candidates (otherwise the expression
9778 // would have 'bound member' type, not 'overload' type).
9779 // Ideally we would note which candidate was chosen and why
9780 // the static candidates were rejected.
9781 SrcExpr = ExprError();
9782 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009783 }
Douglas Gregordb2eae62011-03-16 19:16:25 +00009784
Sylvestre Ledru43e3dee2012-07-31 06:56:50 +00009785 // Fix the expression to refer to 'fn'.
John McCall864c0412011-04-26 20:42:42 +00009786 SingleFunctionExpression =
John McCall6dbba4f2011-10-11 23:14:30 +00009787 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall864c0412011-04-26 20:42:42 +00009788
9789 // If desired, do function-to-pointer decay.
John McCall6dbba4f2011-10-11 23:14:30 +00009790 if (doFunctionPointerConverion) {
John McCall864c0412011-04-26 20:42:42 +00009791 SingleFunctionExpression =
9792 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall6dbba4f2011-10-11 23:14:30 +00009793 if (SingleFunctionExpression.isInvalid()) {
9794 SrcExpr = ExprError();
9795 return true;
9796 }
9797 }
John McCall864c0412011-04-26 20:42:42 +00009798 }
9799
9800 if (!SingleFunctionExpression.isUsable()) {
9801 if (complain) {
9802 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9803 << ovl.Expression->getName()
9804 << DestTypeForComplaining
9805 << OpRangeForComplaining
9806 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall6dbba4f2011-10-11 23:14:30 +00009807 NoteAllOverloadCandidates(SrcExpr.get());
9808
9809 SrcExpr = ExprError();
9810 return true;
9811 }
9812
9813 return false;
John McCall864c0412011-04-26 20:42:42 +00009814 }
9815
John McCall6dbba4f2011-10-11 23:14:30 +00009816 SrcExpr = SingleFunctionExpression;
9817 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009818}
9819
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009820/// \brief Add a single candidate to the overload set.
9821static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00009822 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00009823 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009824 ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009825 OverloadCandidateSet &CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00009826 bool PartialOverloading,
9827 bool KnownValid) {
John McCall9aa472c2010-03-19 07:35:19 +00009828 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00009829 if (isa<UsingShadowDecl>(Callee))
9830 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9831
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009832 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith2ced0442011-06-26 22:19:54 +00009833 if (ExplicitTemplateArgs) {
9834 assert(!KnownValid && "Explicit template arguments?");
9835 return;
9836 }
Ahmed Charles13a140c2012-02-25 11:00:22 +00009837 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9838 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009839 return;
John McCallba135432009-11-21 08:51:07 +00009840 }
9841
9842 if (FunctionTemplateDecl *FuncTemplate
9843 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00009844 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009845 ExplicitTemplateArgs, Args, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00009846 return;
9847 }
9848
Richard Smith2ced0442011-06-26 22:19:54 +00009849 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009850}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009851
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009852/// \brief Add the overload candidates named by callee and/or found by argument
9853/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00009854void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009855 ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009856 OverloadCandidateSet &CandidateSet,
9857 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00009858
9859#ifndef NDEBUG
9860 // Verify that ArgumentDependentLookup is consistent with the rules
9861 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009862 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009863 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9864 // and let Y be the lookup set produced by argument dependent
9865 // lookup (defined as follows). If X contains
9866 //
9867 // -- a declaration of a class member, or
9868 //
9869 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00009870 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009871 //
9872 // -- a declaration that is neither a function or a function
9873 // template
9874 //
9875 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00009876
John McCall3b4294e2009-12-16 12:17:52 +00009877 if (ULE->requiresADL()) {
9878 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9879 E = ULE->decls_end(); I != E; ++I) {
9880 assert(!(*I)->getDeclContext()->isRecord());
9881 assert(isa<UsingShadowDecl>(*I) ||
9882 !(*I)->getDeclContext()->isFunctionOrMethod());
9883 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00009884 }
9885 }
9886#endif
9887
John McCall3b4294e2009-12-16 12:17:52 +00009888 // It would be nice to avoid this copy.
9889 TemplateArgumentListInfo TABuffer;
Douglas Gregor67714232011-03-03 02:41:12 +00009890 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009891 if (ULE->hasExplicitTemplateArgs()) {
9892 ULE->copyTemplateArgumentsInto(TABuffer);
9893 ExplicitTemplateArgs = &TABuffer;
9894 }
9895
9896 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9897 E = ULE->decls_end(); I != E; ++I)
Ahmed Charles13a140c2012-02-25 11:00:22 +00009898 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9899 CandidateSet, PartialOverloading,
9900 /*KnownValid*/ true);
John McCallba135432009-11-21 08:51:07 +00009901
John McCall3b4294e2009-12-16 12:17:52 +00009902 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00009903 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00009904 ULE->getExprLoc(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009905 Args, ExplicitTemplateArgs,
Richard Smithb1502bc2012-10-18 17:56:02 +00009906 CandidateSet, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009907}
John McCall578b69b2009-12-16 08:11:27 +00009908
Richard Smithd3ff3252013-06-12 22:56:54 +00009909/// Determine whether a declaration with the specified name could be moved into
9910/// a different namespace.
9911static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
9912 switch (Name.getCXXOverloadedOperator()) {
9913 case OO_New: case OO_Array_New:
9914 case OO_Delete: case OO_Array_Delete:
9915 return false;
9916
9917 default:
9918 return true;
9919 }
9920}
9921
Richard Smithf50e88a2011-06-05 22:42:48 +00009922/// Attempt to recover from an ill-formed use of a non-dependent name in a
9923/// template, where the non-dependent name was declared after the template
9924/// was defined. This is common in code written for a compilers which do not
9925/// correctly implement two-stage name lookup.
9926///
9927/// Returns true if a viable candidate was found and a diagnostic was issued.
9928static bool
9929DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9930 const CXXScopeSpec &SS, LookupResult &R,
9931 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009932 ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009933 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9934 return false;
9935
9936 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewycky5a7120c2012-03-14 20:41:00 +00009937 if (DC->isTransparentContext())
9938 continue;
9939
Richard Smithf50e88a2011-06-05 22:42:48 +00009940 SemaRef.LookupQualifiedName(R, DC);
9941
9942 if (!R.empty()) {
9943 R.suppressDiagnostics();
9944
9945 if (isa<CXXRecordDecl>(DC)) {
9946 // Don't diagnose names we find in classes; we get much better
9947 // diagnostics for these from DiagnoseEmptyLookup.
9948 R.clear();
9949 return false;
9950 }
9951
9952 OverloadCandidateSet Candidates(FnLoc);
9953 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9954 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009955 ExplicitTemplateArgs, Args,
Richard Smith2ced0442011-06-26 22:19:54 +00009956 Candidates, false, /*KnownValid*/ false);
Richard Smithf50e88a2011-06-05 22:42:48 +00009957
9958 OverloadCandidateSet::iterator Best;
Richard Smith2ced0442011-06-26 22:19:54 +00009959 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009960 // No viable functions. Don't bother the user with notes for functions
9961 // which don't work and shouldn't be found anyway.
Richard Smith2ced0442011-06-26 22:19:54 +00009962 R.clear();
Richard Smithf50e88a2011-06-05 22:42:48 +00009963 return false;
Richard Smith2ced0442011-06-26 22:19:54 +00009964 }
Richard Smithf50e88a2011-06-05 22:42:48 +00009965
9966 // Find the namespaces where ADL would have looked, and suggest
9967 // declaring the function there instead.
9968 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9969 Sema::AssociatedClassSet AssociatedClasses;
John McCall42f48fb2012-08-24 20:38:34 +00009970 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009971 AssociatedNamespaces,
9972 AssociatedClasses);
Chandler Carruth74d487e2011-06-05 23:36:55 +00009973 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smithd3ff3252013-06-12 22:56:54 +00009974 if (canBeDeclaredInNamespace(R.getLookupName())) {
9975 DeclContext *Std = SemaRef.getStdNamespace();
9976 for (Sema::AssociatedNamespaceSet::iterator
9977 it = AssociatedNamespaces.begin(),
9978 end = AssociatedNamespaces.end(); it != end; ++it) {
9979 // Never suggest declaring a function within namespace 'std'.
9980 if (Std && Std->Encloses(*it))
9981 continue;
Richard Smith19e0d952012-12-22 02:46:14 +00009982
Richard Smithd3ff3252013-06-12 22:56:54 +00009983 // Never suggest declaring a function within a namespace with a
9984 // reserved name, like __gnu_cxx.
9985 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
9986 if (NS &&
9987 NS->getQualifiedNameAsString().find("__") != std::string::npos)
9988 continue;
9989
9990 SuggestedNamespaces.insert(*it);
9991 }
Richard Smithf50e88a2011-06-05 22:42:48 +00009992 }
9993
9994 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9995 << R.getLookupName();
Chandler Carruth74d487e2011-06-05 23:36:55 +00009996 if (SuggestedNamespaces.empty()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009997 SemaRef.Diag(Best->Function->getLocation(),
9998 diag::note_not_found_by_two_phase_lookup)
9999 << R.getLookupName() << 0;
Chandler Carruth74d487e2011-06-05 23:36:55 +000010000 } else if (SuggestedNamespaces.size() == 1) {
Richard Smithf50e88a2011-06-05 22:42:48 +000010001 SemaRef.Diag(Best->Function->getLocation(),
10002 diag::note_not_found_by_two_phase_lookup)
Chandler Carruth74d487e2011-06-05 23:36:55 +000010003 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smithf50e88a2011-06-05 22:42:48 +000010004 } else {
10005 // FIXME: It would be useful to list the associated namespaces here,
10006 // but the diagnostics infrastructure doesn't provide a way to produce
10007 // a localized representation of a list of items.
10008 SemaRef.Diag(Best->Function->getLocation(),
10009 diag::note_not_found_by_two_phase_lookup)
10010 << R.getLookupName() << 2;
10011 }
10012
10013 // Try to recover by calling this function.
10014 return true;
10015 }
10016
10017 R.clear();
10018 }
10019
10020 return false;
10021}
10022
10023/// Attempt to recover from ill-formed use of a non-dependent operator in a
10024/// template, where the non-dependent operator was declared after the template
10025/// was defined.
10026///
10027/// Returns true if a viable candidate was found and a diagnostic was issued.
10028static bool
10029DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10030 SourceLocation OpLoc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010031 ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +000010032 DeclarationName OpName =
10033 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10034 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10035 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010036 /*ExplicitTemplateArgs=*/0, Args);
Richard Smithf50e88a2011-06-05 22:42:48 +000010037}
10038
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +000010039namespace {
Richard Smithe49ff3e2012-09-25 04:46:05 +000010040class BuildRecoveryCallExprRAII {
10041 Sema &SemaRef;
10042public:
10043 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10044 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10045 SemaRef.IsBuildingRecoveryCallExpr = true;
10046 }
10047
10048 ~BuildRecoveryCallExprRAII() {
10049 SemaRef.IsBuildingRecoveryCallExpr = false;
10050 }
10051};
10052
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +000010053}
10054
John McCall578b69b2009-12-16 08:11:27 +000010055/// Attempts to recover from a call where no functions were found.
10056///
10057/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +000010058static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +000010059BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +000010060 UnresolvedLookupExpr *ULE,
10061 SourceLocation LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010062 llvm::MutableArrayRef<Expr *> Args,
Richard Smithf50e88a2011-06-05 22:42:48 +000010063 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +000010064 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smithe49ff3e2012-09-25 04:46:05 +000010065 // Do not try to recover if it is already building a recovery call.
10066 // This stops infinite loops for template instantiations like
10067 //
10068 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10069 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10070 //
10071 if (SemaRef.IsBuildingRecoveryCallExpr)
10072 return ExprError();
10073 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCall578b69b2009-12-16 08:11:27 +000010074
10075 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +000010076 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnarae4b92762012-01-27 09:46:47 +000010077 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCall578b69b2009-12-16 08:11:27 +000010078
John McCall3b4294e2009-12-16 12:17:52 +000010079 TemplateArgumentListInfo TABuffer;
Richard Smithf50e88a2011-06-05 22:42:48 +000010080 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +000010081 if (ULE->hasExplicitTemplateArgs()) {
10082 ULE->copyTemplateArgumentsInto(TABuffer);
10083 ExplicitTemplateArgs = &TABuffer;
10084 }
10085
John McCall578b69b2009-12-16 08:11:27 +000010086 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10087 Sema::LookupOrdinaryName);
Kaelyn Uhrain761695f2013-07-08 23:13:39 +000010088 FunctionCallFilterCCC Validator(SemaRef, Args.size(),
10089 ExplicitTemplateArgs != 0);
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +000010090 NoTypoCorrectionCCC RejectAll;
10091 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
10092 (CorrectionCandidateCallback*)&Validator :
10093 (CorrectionCandidateCallback*)&RejectAll;
Richard Smithf50e88a2011-06-05 22:42:48 +000010094 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010095 ExplicitTemplateArgs, Args) &&
Richard Smithf50e88a2011-06-05 22:42:48 +000010096 (!EmptyLookup ||
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +000010097 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010098 ExplicitTemplateArgs, Args)))
John McCallf312b1e2010-08-26 23:41:50 +000010099 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +000010100
John McCall3b4294e2009-12-16 12:17:52 +000010101 assert(!R.empty() && "lookup results empty despite recovery");
10102
10103 // Build an implicit member call if appropriate. Just drop the
10104 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +000010105 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +000010106 if ((*R.begin())->isCXXClassMember())
Abramo Bagnarae4b92762012-01-27 09:46:47 +000010107 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
10108 R, ExplicitTemplateArgs);
Abramo Bagnara9d9922a2012-02-06 14:31:00 +000010109 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnarae4b92762012-01-27 09:46:47 +000010110 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara9d9922a2012-02-06 14:31:00 +000010111 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +000010112 else
10113 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10114
10115 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +000010116 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +000010117
10118 // This shouldn't cause an infinite loop because we're giving it
Richard Smithf50e88a2011-06-05 22:42:48 +000010119 // an expression with viable lookup results, which should never
John McCall3b4294e2009-12-16 12:17:52 +000010120 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +000010121 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010122 MultiExprArg(Args.data(), Args.size()),
10123 RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +000010124}
Douglas Gregord7a95972010-06-08 17:35:15 +000010125
Sam Panzere1715b62012-08-21 00:52:01 +000010126/// \brief Constructs and populates an OverloadedCandidateSet from
10127/// the given function.
10128/// \returns true when an the ExprResult output parameter has been set.
10129bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10130 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010131 MultiExprArg Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010132 SourceLocation RParenLoc,
10133 OverloadCandidateSet *CandidateSet,
10134 ExprResult *Result) {
John McCall3b4294e2009-12-16 12:17:52 +000010135#ifndef NDEBUG
10136 if (ULE->requiresADL()) {
10137 // To do ADL, we must have found an unqualified name.
10138 assert(!ULE->getQualifier() && "qualified name with ADL");
10139
10140 // We don't perform ADL for implicit declarations of builtins.
10141 // Verify that this was correctly set up.
10142 FunctionDecl *F;
10143 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10144 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10145 F->getBuiltinID() && F->isImplicit())
David Blaikieb219cfc2011-09-23 05:06:16 +000010146 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010147
John McCall3b4294e2009-12-16 12:17:52 +000010148 // We don't perform ADL in C.
David Blaikie4e4d0842012-03-11 07:00:24 +000010149 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb1502bc2012-10-18 17:56:02 +000010150 }
John McCall3b4294e2009-12-16 12:17:52 +000010151#endif
10152
John McCall5acb0c92011-10-17 18:40:02 +000010153 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010154 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzere1715b62012-08-21 00:52:01 +000010155 *Result = ExprError();
10156 return true;
10157 }
Douglas Gregor17330012009-02-04 15:01:18 +000010158
John McCall3b4294e2009-12-16 12:17:52 +000010159 // Add the functions denoted by the callee to the set of candidate
10160 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010161 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +000010162
10163 // If we found nothing, try to recover.
Richard Smithf50e88a2011-06-05 22:42:48 +000010164 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
10165 // out if it fails.
Sam Panzere1715b62012-08-21 00:52:01 +000010166 if (CandidateSet->empty()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +000010167 // In Microsoft mode, if we are inside a template class member function then
10168 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichet0f74d1e2011-09-07 00:14:57 +000010169 // to instantiation time to be able to search into type dependent base
Sebastian Redl14b0c192011-09-24 17:48:00 +000010170 // classes.
David Blaikie4e4d0842012-03-11 07:00:24 +000010171 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetc8ff9152011-11-25 01:10:54 +000010172 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010173 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010174 Context.DependentTy, VK_RValue,
10175 RParenLoc);
Sebastian Redl14b0c192011-09-24 17:48:00 +000010176 CE->setTypeDependent(true);
Sam Panzere1715b62012-08-21 00:52:01 +000010177 *Result = Owned(CE);
10178 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +000010179 }
Sam Panzere1715b62012-08-21 00:52:01 +000010180 return false;
Francois Pichet0f74d1e2011-09-07 00:14:57 +000010181 }
John McCall578b69b2009-12-16 08:11:27 +000010182
John McCall5acb0c92011-10-17 18:40:02 +000010183 UnbridgedCasts.restore();
Sam Panzere1715b62012-08-21 00:52:01 +000010184 return false;
10185}
John McCall5acb0c92011-10-17 18:40:02 +000010186
Sam Panzere1715b62012-08-21 00:52:01 +000010187/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10188/// the completed call expression. If overload resolution fails, emits
10189/// diagnostics and returns ExprError()
10190static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10191 UnresolvedLookupExpr *ULE,
10192 SourceLocation LParenLoc,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010193 MultiExprArg Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010194 SourceLocation RParenLoc,
10195 Expr *ExecConfig,
10196 OverloadCandidateSet *CandidateSet,
10197 OverloadCandidateSet::iterator *Best,
10198 OverloadingResult OverloadResult,
10199 bool AllowTypoCorrection) {
10200 if (CandidateSet->empty())
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010201 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010202 RParenLoc, /*EmptyLookup=*/true,
10203 AllowTypoCorrection);
10204
10205 switch (OverloadResult) {
John McCall3b4294e2009-12-16 12:17:52 +000010206 case OR_Success: {
Sam Panzere1715b62012-08-21 00:52:01 +000010207 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzere1715b62012-08-21 00:52:01 +000010208 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +000010209 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10210 return ExprError();
Sam Panzere1715b62012-08-21 00:52:01 +000010211 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010212 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10213 ExecConfig);
John McCall3b4294e2009-12-16 12:17:52 +000010214 }
Douglas Gregorf6b89692008-11-26 05:54:23 +000010215
Richard Smithf50e88a2011-06-05 22:42:48 +000010216 case OR_No_Viable_Function: {
10217 // Try to recover by looking for viable functions which the user might
10218 // have meant to call.
Sam Panzere1715b62012-08-21 00:52:01 +000010219 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010220 Args, RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +000010221 /*EmptyLookup=*/false,
10222 AllowTypoCorrection);
Richard Smithf50e88a2011-06-05 22:42:48 +000010223 if (!Recovery.isInvalid())
10224 return Recovery;
10225
Sam Panzere1715b62012-08-21 00:52:01 +000010226 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregorf6b89692008-11-26 05:54:23 +000010227 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +000010228 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010229 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregorf6b89692008-11-26 05:54:23 +000010230 break;
Richard Smithf50e88a2011-06-05 22:42:48 +000010231 }
Douglas Gregorf6b89692008-11-26 05:54:23 +000010232
10233 case OR_Ambiguous:
Sam Panzere1715b62012-08-21 00:52:01 +000010234 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +000010235 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010236 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregorf6b89692008-11-26 05:54:23 +000010237 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010238
Sam Panzere1715b62012-08-21 00:52:01 +000010239 case OR_Deleted: {
10240 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10241 << (*Best)->Function->isDeleted()
10242 << ULE->getName()
10243 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10244 << Fn->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010245 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis0d579b62011-11-04 15:58:13 +000010246
Sam Panzere1715b62012-08-21 00:52:01 +000010247 // We emitted an error for the unvailable/deleted function call but keep
10248 // the call in the AST.
10249 FunctionDecl *FDecl = (*Best)->Function;
10250 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010251 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10252 ExecConfig);
Sam Panzere1715b62012-08-21 00:52:01 +000010253 }
Douglas Gregorf6b89692008-11-26 05:54:23 +000010254 }
10255
Douglas Gregorff331c12010-07-25 18:17:45 +000010256 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +000010257 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +000010258}
10259
Sam Panzere1715b62012-08-21 00:52:01 +000010260/// BuildOverloadedCallExpr - Given the call expression that calls Fn
10261/// (which eventually refers to the declaration Func) and the call
10262/// arguments Args/NumArgs, attempt to resolve the function call down
10263/// to a specific function. If overload resolution succeeds, returns
10264/// the call expression produced by overload resolution.
10265/// Otherwise, emits diagnostics and returns ExprError.
10266ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10267 UnresolvedLookupExpr *ULE,
10268 SourceLocation LParenLoc,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010269 MultiExprArg Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010270 SourceLocation RParenLoc,
10271 Expr *ExecConfig,
10272 bool AllowTypoCorrection) {
10273 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
10274 ExprResult result;
10275
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010276 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10277 &result))
Sam Panzere1715b62012-08-21 00:52:01 +000010278 return result;
10279
10280 OverloadCandidateSet::iterator Best;
10281 OverloadingResult OverloadResult =
10282 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10283
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010284 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010285 RParenLoc, ExecConfig, &CandidateSet,
10286 &Best, OverloadResult,
10287 AllowTypoCorrection);
10288}
10289
John McCall6e266892010-01-26 03:27:55 +000010290static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +000010291 return Functions.size() > 1 ||
10292 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10293}
10294
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010295/// \brief Create a unary operation that may resolve to an overloaded
10296/// operator.
10297///
10298/// \param OpLoc The location of the operator itself (e.g., '*').
10299///
10300/// \param OpcIn The UnaryOperator::Opcode that describes this
10301/// operator.
10302///
James Dennett40ae6662012-06-22 08:52:37 +000010303/// \param Fns The set of non-member functions that will be
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010304/// considered by overload resolution. The caller needs to build this
10305/// set based on the context using, e.g.,
10306/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10307/// set should not contain any member functions; those will be added
10308/// by CreateOverloadedUnaryOp().
10309///
James Dennett8da16872012-06-22 10:32:46 +000010310/// \param Input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010311ExprResult
John McCall6e266892010-01-26 03:27:55 +000010312Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10313 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +000010314 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010315 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010316
10317 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10318 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10319 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +000010320 // TODO: provide better source location info.
10321 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010322
John McCall5acb0c92011-10-17 18:40:02 +000010323 if (checkPlaceholderForOverload(*this, Input))
10324 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010325
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010326 Expr *Args[2] = { Input, 0 };
10327 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +000010328
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010329 // For post-increment and post-decrement, add the implicit '0' as
10330 // the second argument, so that we know this is a post-increment or
10331 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +000010332 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010333 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +000010334 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10335 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010336 NumArgs = 2;
10337 }
10338
Richard Smith958ba642013-05-05 15:51:06 +000010339 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10340
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010341 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010342 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +000010343 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010344 Opc,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010345 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010346 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010347 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010348
John McCallc373d482010-01-27 01:50:18 +000010349 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +000010350 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010351 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010352 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010353 /*ADL*/ true, IsOverloaded(Fns),
10354 Fns.begin(), Fns.end());
Richard Smith958ba642013-05-05 15:51:06 +000010355 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, ArgsArray,
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010356 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010357 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +000010358 OpLoc, false));
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010359 }
10360
10361 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010362 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010363
10364 // Add the candidates from the given function set.
Richard Smith958ba642013-05-05 15:51:06 +000010365 AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010366
10367 // Add operator candidates that are member functions.
Richard Smith958ba642013-05-05 15:51:06 +000010368 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010369
John McCall6e266892010-01-26 03:27:55 +000010370 // Add candidates from ADL.
Richard Smith958ba642013-05-05 15:51:06 +000010371 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, OpLoc,
10372 ArgsArray, /*ExplicitTemplateArgs*/ 0,
John McCall6e266892010-01-26 03:27:55 +000010373 CandidateSet);
10374
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010375 // Add builtin operator candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010376 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010377
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010378 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10379
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010380 // Perform overload resolution.
10381 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010382 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010383 case OR_Success: {
10384 // We found a built-in operator or an overloaded operator.
10385 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +000010386
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010387 if (FnDecl) {
10388 // We matched an overloaded operator. Build a call to that
10389 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +000010390
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010391 // Convert the arguments.
10392 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +000010393 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010394
John Wiegley429bb272011-04-08 18:41:53 +000010395 ExprResult InputRes =
10396 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10397 Best->FoundDecl, Method);
10398 if (InputRes.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010399 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010400 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010401 } else {
10402 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010403 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +000010404 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010405 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +000010406 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010407 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +000010408 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +000010409 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010410 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +000010411 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010412 }
10413
John McCallf89e55a2010-11-18 06:31:45 +000010414 // Determine the result type.
10415 QualType ResultTy = FnDecl->getResultType();
10416 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10417 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +000010418
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010419 // Build the actual expression node.
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010420 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010421 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010422 if (FnExpr.isInvalid())
10423 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +000010424
Eli Friedman4c3b8962009-11-18 03:58:17 +000010425 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +000010426 CallExpr *TheCall =
Richard Smith958ba642013-05-05 15:51:06 +000010427 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), ArgsArray,
Lang Hamesbe9af122012-10-02 04:45:10 +000010428 ResultTy, VK, OpLoc, false);
John McCallb697e082010-05-06 18:15:07 +000010429
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010430 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +000010431 FnDecl))
10432 return ExprError();
10433
John McCall9ae2f072010-08-23 23:25:46 +000010434 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010435 } else {
10436 // We matched a built-in operator. Convert the arguments, then
10437 // break out so that we will build the appropriate built-in
10438 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010439 ExprResult InputRes =
10440 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10441 Best->Conversions[0], AA_Passing);
10442 if (InputRes.isInvalid())
10443 return ExprError();
10444 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010445 break;
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010446 }
John Wiegley429bb272011-04-08 18:41:53 +000010447 }
10448
10449 case OR_No_Viable_Function:
Richard Smithf50e88a2011-06-05 22:42:48 +000010450 // This is an erroneous use of an operator which can be overloaded by
10451 // a non-member function. Check for non-member operators which were
10452 // defined too late to be candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010453 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smithf50e88a2011-06-05 22:42:48 +000010454 // FIXME: Recover by calling the found function.
10455 return ExprError();
10456
John Wiegley429bb272011-04-08 18:41:53 +000010457 // No viable function; fall through to handling this as a
10458 // built-in operator, which will produce an error message for us.
10459 break;
10460
10461 case OR_Ambiguous:
10462 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10463 << UnaryOperator::getOpcodeStr(Opc)
10464 << Input->getType()
10465 << Input->getSourceRange();
Richard Smith958ba642013-05-05 15:51:06 +000010466 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley429bb272011-04-08 18:41:53 +000010467 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10468 return ExprError();
10469
10470 case OR_Deleted:
10471 Diag(OpLoc, diag::err_ovl_deleted_oper)
10472 << Best->Function->isDeleted()
10473 << UnaryOperator::getOpcodeStr(Opc)
10474 << getDeletedOrUnavailableSuffix(Best->Function)
10475 << Input->getSourceRange();
Richard Smith958ba642013-05-05 15:51:06 +000010476 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman1795d372011-08-26 19:46:22 +000010477 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010478 return ExprError();
10479 }
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010480
10481 // Either we found no viable overloaded operator or we matched a
10482 // built-in operator. In either case, fall through to trying to
10483 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +000010484 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010485}
10486
Douglas Gregor063daf62009-03-13 18:40:31 +000010487/// \brief Create a binary operation that may resolve to an overloaded
10488/// operator.
10489///
10490/// \param OpLoc The location of the operator itself (e.g., '+').
10491///
10492/// \param OpcIn The BinaryOperator::Opcode that describes this
10493/// operator.
10494///
James Dennett40ae6662012-06-22 08:52:37 +000010495/// \param Fns The set of non-member functions that will be
Douglas Gregor063daf62009-03-13 18:40:31 +000010496/// considered by overload resolution. The caller needs to build this
10497/// set based on the context using, e.g.,
10498/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10499/// set should not contain any member functions; those will be added
10500/// by CreateOverloadedBinOp().
10501///
10502/// \param LHS Left-hand argument.
10503/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010504ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +000010505Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +000010506 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +000010507 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +000010508 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +000010509 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010510 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +000010511
10512 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10513 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10514 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10515
10516 // If either side is type-dependent, create an appropriate dependent
10517 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010518 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +000010519 if (Fns.empty()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010520 // If there are no functions to store, just build a dependent
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010521 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +000010522 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010523 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +000010524 Context.DependentTy,
10525 VK_RValue, OK_Ordinary,
Lang Hamesbe9af122012-10-02 04:45:10 +000010526 OpLoc,
10527 FPFeatures.fp_contract));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010528
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010529 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10530 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010531 VK_LValue,
10532 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010533 Context.DependentTy,
10534 Context.DependentTy,
Lang Hamesbe9af122012-10-02 04:45:10 +000010535 OpLoc,
10536 FPFeatures.fp_contract));
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010537 }
John McCall6e266892010-01-26 03:27:55 +000010538
10539 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +000010540 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010541 // TODO: provide better source location info in DNLoc component.
10542 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +000010543 UnresolvedLookupExpr *Fn
Douglas Gregor4c9be892011-02-28 20:01:57 +000010544 = UnresolvedLookupExpr::Create(Context, NamingClass,
10545 NestedNameSpecifierLoc(), OpNameInfo,
10546 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010547 Fns.begin(), Fns.end());
Lang Hamesbe9af122012-10-02 04:45:10 +000010548 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10549 Context.DependentTy, VK_RValue,
10550 OpLoc, FPFeatures.fp_contract));
Douglas Gregor063daf62009-03-13 18:40:31 +000010551 }
10552
John McCall5acb0c92011-10-17 18:40:02 +000010553 // Always do placeholder-like conversions on the RHS.
10554 if (checkPlaceholderForOverload(*this, Args[1]))
10555 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010556
John McCall3c3b7f92011-10-25 17:37:35 +000010557 // Do placeholder-like conversion on the LHS; note that we should
10558 // not get here with a PseudoObject LHS.
10559 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall5acb0c92011-10-17 18:40:02 +000010560 if (checkPlaceholderForOverload(*this, Args[0]))
10561 return ExprError();
10562
Sebastian Redl275c2b42009-11-18 23:10:33 +000010563 // If this is the assignment operator, we only perform overload resolution
10564 // if the left-hand side is a class or enumeration type. This is actually
10565 // a hack. The standard requires that we do overload resolution between the
10566 // various built-in candidates, but as DR507 points out, this can lead to
10567 // problems. So we do it this way, which pretty much follows what GCC does.
10568 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +000010569 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010570 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010571
John McCall0e800c92010-12-04 08:14:53 +000010572 // If this is the .* operator, which is not overloadable, just
10573 // create a built-in binary operator.
10574 if (Opc == BO_PtrMemD)
10575 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10576
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010577 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010578 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010579
10580 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010581 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +000010582
10583 // Add operator candidates that are member functions.
Richard Smith958ba642013-05-05 15:51:06 +000010584 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +000010585
John McCall6e266892010-01-26 03:27:55 +000010586 // Add candidates from ADL.
10587 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010588 OpLoc, Args,
John McCall6e266892010-01-26 03:27:55 +000010589 /*ExplicitTemplateArgs*/ 0,
10590 CandidateSet);
10591
Douglas Gregor063daf62009-03-13 18:40:31 +000010592 // Add builtin operator candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010593 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +000010594
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010595 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10596
Douglas Gregor063daf62009-03-13 18:40:31 +000010597 // Perform overload resolution.
10598 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010599 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +000010600 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +000010601 // We found a built-in operator or an overloaded operator.
10602 FunctionDecl *FnDecl = Best->Function;
10603
10604 if (FnDecl) {
10605 // We matched an overloaded operator. Build a call to that
10606 // operator.
10607
10608 // Convert the arguments.
10609 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +000010610 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +000010611 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010612
Chandler Carruth6df868e2010-12-12 08:17:55 +000010613 ExprResult Arg1 =
10614 PerformCopyInitialization(
10615 InitializedEntity::InitializeParameter(Context,
10616 FnDecl->getParamDecl(0)),
10617 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010618 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010619 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010620
John Wiegley429bb272011-04-08 18:41:53 +000010621 ExprResult Arg0 =
10622 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10623 Best->FoundDecl, Method);
10624 if (Arg0.isInvalid())
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010625 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010626 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010627 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010628 } else {
10629 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +000010630 ExprResult Arg0 = PerformCopyInitialization(
10631 InitializedEntity::InitializeParameter(Context,
10632 FnDecl->getParamDecl(0)),
10633 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010634 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010635 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010636
Chandler Carruth6df868e2010-12-12 08:17:55 +000010637 ExprResult Arg1 =
10638 PerformCopyInitialization(
10639 InitializedEntity::InitializeParameter(Context,
10640 FnDecl->getParamDecl(1)),
10641 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010642 if (Arg1.isInvalid())
10643 return ExprError();
10644 Args[0] = LHS = Arg0.takeAs<Expr>();
10645 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010646 }
10647
John McCallf89e55a2010-11-18 06:31:45 +000010648 // Determine the result type.
10649 QualType ResultTy = FnDecl->getResultType();
10650 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10651 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +000010652
10653 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010654 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010655 Best->FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010656 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010657 if (FnExpr.isInvalid())
10658 return ExprError();
Douglas Gregor063daf62009-03-13 18:40:31 +000010659
John McCall9ae2f072010-08-23 23:25:46 +000010660 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010661 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000010662 Args, ResultTy, VK, OpLoc,
10663 FPFeatures.fp_contract);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010664
10665 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000010666 FnDecl))
10667 return ExprError();
10668
Nick Lewycky9b7ea0d2013-01-24 02:03:08 +000010669 ArrayRef<const Expr *> ArgsArray(Args, 2);
10670 // Cut off the implicit 'this'.
10671 if (isa<CXXMethodDecl>(FnDecl))
10672 ArgsArray = ArgsArray.slice(1);
10673 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
10674 TheCall->getSourceRange(), VariadicDoesNotApply);
10675
John McCall9ae2f072010-08-23 23:25:46 +000010676 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +000010677 } else {
10678 // We matched a built-in operator. Convert the arguments, then
10679 // break out so that we will build the appropriate built-in
10680 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010681 ExprResult ArgsRes0 =
10682 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10683 Best->Conversions[0], AA_Passing);
10684 if (ArgsRes0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010685 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010686 Args[0] = ArgsRes0.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010687
John Wiegley429bb272011-04-08 18:41:53 +000010688 ExprResult ArgsRes1 =
10689 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10690 Best->Conversions[1], AA_Passing);
10691 if (ArgsRes1.isInvalid())
10692 return ExprError();
10693 Args[1] = ArgsRes1.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010694 break;
10695 }
10696 }
10697
Douglas Gregor33074752009-09-30 21:46:01 +000010698 case OR_No_Viable_Function: {
10699 // C++ [over.match.oper]p9:
10700 // If the operator is the operator , [...] and there are no
10701 // viable functions, then the operator is assumed to be the
10702 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +000010703 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +000010704 break;
10705
Chandler Carruth6df868e2010-12-12 08:17:55 +000010706 // For class as left operand for assignment or compound assigment
10707 // operator do not fall through to handling in built-in, but report that
10708 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +000010709 ExprResult Result = ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010710 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +000010711 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +000010712 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10713 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010714 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +000010715 } else {
Richard Smithf50e88a2011-06-05 22:42:48 +000010716 // This is an erroneous use of an operator which can be overloaded by
10717 // a non-member function. Check for non-member operators which were
10718 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010719 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smithf50e88a2011-06-05 22:42:48 +000010720 // FIXME: Recover by calling the found function.
10721 return ExprError();
10722
Douglas Gregor33074752009-09-30 21:46:01 +000010723 // No viable function; try to create a built-in operation, which will
10724 // produce an error. Then, show the non-viable candidates.
10725 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +000010726 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010727 assert(Result.isInvalid() &&
Douglas Gregor33074752009-09-30 21:46:01 +000010728 "C++ binary operator overloading is missing candidates!");
10729 if (Result.isInvalid())
Ahmed Charles13a140c2012-02-25 11:00:22 +000010730 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010731 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010732 return Result;
Douglas Gregor33074752009-09-30 21:46:01 +000010733 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010734
10735 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010736 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +000010737 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +000010738 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010739 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010740 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010741 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010742 return ExprError();
10743
10744 case OR_Deleted:
Douglas Gregore4e68d42012-02-15 19:33:52 +000010745 if (isImplicitlyDeleted(Best->Function)) {
10746 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10747 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smith0f46e642012-12-28 12:23:24 +000010748 << Context.getRecordType(Method->getParent())
10749 << getSpecialMember(Method);
Richard Smith5bdaac52012-04-02 20:59:25 +000010750
Richard Smith0f46e642012-12-28 12:23:24 +000010751 // The user probably meant to call this special member. Just
10752 // explain why it's deleted.
10753 NoteDeletedFunction(Method);
10754 return ExprError();
Douglas Gregore4e68d42012-02-15 19:33:52 +000010755 } else {
10756 Diag(OpLoc, diag::err_ovl_deleted_oper)
10757 << Best->Function->isDeleted()
10758 << BinaryOperator::getOpcodeStr(Opc)
10759 << getDeletedOrUnavailableSuffix(Best->Function)
10760 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10761 }
Ahmed Charles13a140c2012-02-25 11:00:22 +000010762 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman1795d372011-08-26 19:46:22 +000010763 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010764 return ExprError();
John McCall1d318332010-01-12 00:44:57 +000010765 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010766
Douglas Gregor33074752009-09-30 21:46:01 +000010767 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010768 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010769}
10770
John McCall60d7b3a2010-08-24 06:29:42 +000010771ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +000010772Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10773 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010774 Expr *Base, Expr *Idx) {
10775 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +000010776 DeclarationName OpName =
10777 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10778
10779 // If either side is type-dependent, create an appropriate dependent
10780 // expression.
10781 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10782
John McCallc373d482010-01-27 01:50:18 +000010783 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010784 // CHECKME: no 'operator' keyword?
10785 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10786 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +000010787 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010788 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010789 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010790 /*ADL*/ true, /*Overloaded*/ false,
10791 UnresolvedSetIterator(),
10792 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +000010793 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +000010794
Sebastian Redlf322ed62009-10-29 20:17:01 +000010795 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010796 Args,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010797 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010798 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +000010799 RLoc, false));
Sebastian Redlf322ed62009-10-29 20:17:01 +000010800 }
10801
John McCall5acb0c92011-10-17 18:40:02 +000010802 // Handle placeholders on both operands.
10803 if (checkPlaceholderForOverload(*this, Args[0]))
10804 return ExprError();
10805 if (checkPlaceholderForOverload(*this, Args[1]))
10806 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010807
Sebastian Redlf322ed62009-10-29 20:17:01 +000010808 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010809 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010810
10811 // Subscript can only be overloaded as a member function.
10812
10813 // Add operator candidates that are member functions.
Richard Smith958ba642013-05-05 15:51:06 +000010814 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010815
10816 // Add builtin operator candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010817 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010818
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010819 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10820
Sebastian Redlf322ed62009-10-29 20:17:01 +000010821 // Perform overload resolution.
10822 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010823 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +000010824 case OR_Success: {
10825 // We found a built-in operator or an overloaded operator.
10826 FunctionDecl *FnDecl = Best->Function;
10827
10828 if (FnDecl) {
10829 // We matched an overloaded operator. Build a call to that
10830 // operator.
10831
John McCall9aa472c2010-03-19 07:35:19 +000010832 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallc373d482010-01-27 01:50:18 +000010833
Sebastian Redlf322ed62009-10-29 20:17:01 +000010834 // Convert the arguments.
10835 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley429bb272011-04-08 18:41:53 +000010836 ExprResult Arg0 =
10837 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10838 Best->FoundDecl, Method);
10839 if (Arg0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010840 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010841 Args[0] = Arg0.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010842
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010843 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010844 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010845 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010846 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010847 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010848 SourceLocation(),
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010849 Owned(Args[1]));
10850 if (InputInit.isInvalid())
10851 return ExprError();
10852
10853 Args[1] = InputInit.takeAs<Expr>();
10854
Sebastian Redlf322ed62009-10-29 20:17:01 +000010855 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +000010856 QualType ResultTy = FnDecl->getResultType();
10857 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10858 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010859
10860 // Build the actual expression node.
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010861 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10862 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010863 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010864 Best->FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010865 HadMultipleCandidates,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010866 OpLocInfo.getLoc(),
10867 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010868 if (FnExpr.isInvalid())
10869 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010870
John McCall9ae2f072010-08-23 23:25:46 +000010871 CXXOperatorCallExpr *TheCall =
10872 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010873 FnExpr.take(), Args,
Lang Hamesbe9af122012-10-02 04:45:10 +000010874 ResultTy, VK, RLoc,
10875 false);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010876
John McCall9ae2f072010-08-23 23:25:46 +000010877 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010878 FnDecl))
10879 return ExprError();
10880
John McCall9ae2f072010-08-23 23:25:46 +000010881 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010882 } else {
10883 // We matched a built-in operator. Convert the arguments, then
10884 // break out so that we will build the appropriate built-in
10885 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010886 ExprResult ArgsRes0 =
10887 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10888 Best->Conversions[0], AA_Passing);
10889 if (ArgsRes0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010890 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010891 Args[0] = ArgsRes0.take();
10892
10893 ExprResult ArgsRes1 =
10894 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10895 Best->Conversions[1], AA_Passing);
10896 if (ArgsRes1.isInvalid())
10897 return ExprError();
10898 Args[1] = ArgsRes1.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010899
10900 break;
10901 }
10902 }
10903
10904 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +000010905 if (CandidateSet.empty())
10906 Diag(LLoc, diag::err_ovl_no_oper)
10907 << Args[0]->getType() << /*subscript*/ 0
10908 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10909 else
10910 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10911 << Args[0]->getType()
10912 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010913 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010914 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +000010915 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010916 }
10917
10918 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010919 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010920 << "[]"
Douglas Gregorae2cf762010-11-13 20:06:38 +000010921 << Args[0]->getType() << Args[1]->getType()
10922 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010923 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010924 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010925 return ExprError();
10926
10927 case OR_Deleted:
10928 Diag(LLoc, diag::err_ovl_deleted_oper)
10929 << Best->Function->isDeleted() << "[]"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010930 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redlf322ed62009-10-29 20:17:01 +000010931 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010932 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010933 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010934 return ExprError();
10935 }
10936
10937 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +000010938 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010939}
10940
Douglas Gregor88a35142008-12-22 05:46:06 +000010941/// BuildCallToMemberFunction - Build a call to a member
10942/// function. MemExpr is the expression that refers to the member
10943/// function (and includes the object parameter), Args/NumArgs are the
10944/// arguments to the function call (not including the object
10945/// parameter). The caller needs to validate that the member
John McCall864c0412011-04-26 20:42:42 +000010946/// expression refers to a non-static member function or an overloaded
10947/// member function.
John McCall60d7b3a2010-08-24 06:29:42 +000010948ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +000010949Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010950 SourceLocation LParenLoc,
10951 MultiExprArg Args,
10952 SourceLocation RParenLoc) {
John McCall864c0412011-04-26 20:42:42 +000010953 assert(MemExprE->getType() == Context.BoundMemberTy ||
10954 MemExprE->getType() == Context.OverloadTy);
10955
Douglas Gregor88a35142008-12-22 05:46:06 +000010956 // Dig out the member expression. This holds both the object
10957 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +000010958 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010959
John McCall864c0412011-04-26 20:42:42 +000010960 // Determine whether this is a call to a pointer-to-member function.
10961 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10962 assert(op->getType() == Context.BoundMemberTy);
10963 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10964
10965 QualType fnType =
10966 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10967
10968 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10969 QualType resultType = proto->getCallResultType(Context);
10970 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10971
10972 // Check that the object type isn't more qualified than the
10973 // member function we're calling.
10974 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10975
10976 QualType objectType = op->getLHS()->getType();
10977 if (op->getOpcode() == BO_PtrMemI)
10978 objectType = objectType->castAs<PointerType>()->getPointeeType();
10979 Qualifiers objectQuals = objectType.getQualifiers();
10980
10981 Qualifiers difference = objectQuals - funcQuals;
10982 difference.removeObjCGCAttr();
10983 difference.removeAddressSpace();
10984 if (difference) {
10985 std::string qualsString = difference.getAsString();
10986 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10987 << fnType.getUnqualifiedType()
10988 << qualsString
10989 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10990 }
10991
10992 CXXMemberCallExpr *call
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010993 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall864c0412011-04-26 20:42:42 +000010994 resultType, valueKind, RParenLoc);
10995
10996 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +000010997 op->getRHS()->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +000010998 call, 0))
10999 return ExprError();
11000
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011001 if (ConvertArgumentsForCall(call, op, 0, proto, Args, RParenLoc))
John McCall864c0412011-04-26 20:42:42 +000011002 return ExprError();
11003
Richard Trieue2a90b82013-06-22 02:30:38 +000011004 if (CheckOtherCall(call, proto))
11005 return ExprError();
11006
John McCall864c0412011-04-26 20:42:42 +000011007 return MaybeBindToTemporary(call);
11008 }
11009
John McCall5acb0c92011-10-17 18:40:02 +000011010 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011011 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall5acb0c92011-10-17 18:40:02 +000011012 return ExprError();
11013
John McCall129e2df2009-11-30 22:42:35 +000011014 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +000011015 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +000011016 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +000011017 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +000011018 if (isa<MemberExpr>(NakedMemExpr)) {
11019 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +000011020 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +000011021 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +000011022 Qualifier = MemExpr->getQualifier();
John McCall5acb0c92011-10-17 18:40:02 +000011023 UnbridgedCasts.restore();
John McCall129e2df2009-11-30 22:42:35 +000011024 } else {
11025 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +000011026 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011027
John McCall701c89e2009-12-03 04:06:58 +000011028 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011029 Expr::Classification ObjectClassification
11030 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11031 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +000011032
Douglas Gregor88a35142008-12-22 05:46:06 +000011033 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +000011034 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +000011035
John McCallaa81e162009-12-01 22:10:20 +000011036 // FIXME: avoid copy.
11037 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11038 if (UnresExpr->hasExplicitTemplateArgs()) {
11039 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11040 TemplateArgs = &TemplateArgsBuffer;
11041 }
11042
John McCall129e2df2009-11-30 22:42:35 +000011043 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11044 E = UnresExpr->decls_end(); I != E; ++I) {
11045
John McCall701c89e2009-12-03 04:06:58 +000011046 NamedDecl *Func = *I;
11047 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11048 if (isa<UsingShadowDecl>(Func))
11049 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11050
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011051
Francois Pichetdbee3412011-01-18 05:04:39 +000011052 // Microsoft supports direct constructor calls.
David Blaikie4e4d0842012-03-11 07:00:24 +000011053 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charles13a140c2012-02-25 11:00:22 +000011054 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011055 Args, CandidateSet);
Francois Pichetdbee3412011-01-18 05:04:39 +000011056 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000011057 // If explicit template arguments were provided, we can't call a
11058 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +000011059 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000011060 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011061
John McCall9aa472c2010-03-19 07:35:19 +000011062 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011063 ObjectClassification, Args, CandidateSet,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011064 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000011065 } else {
John McCall129e2df2009-11-30 22:42:35 +000011066 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +000011067 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011068 ObjectType, ObjectClassification,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011069 Args, CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +000011070 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000011071 }
Douglas Gregordec06662009-08-21 18:42:58 +000011072 }
Mike Stump1eb44332009-09-09 15:08:12 +000011073
John McCall129e2df2009-11-30 22:42:35 +000011074 DeclarationName DeclName = UnresExpr->getMemberName();
11075
John McCall5acb0c92011-10-17 18:40:02 +000011076 UnbridgedCasts.restore();
11077
Douglas Gregor88a35142008-12-22 05:46:06 +000011078 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000011079 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +000011080 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +000011081 case OR_Success:
11082 Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +000011083 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +000011084 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +000011085 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11086 return ExprError();
Faisal Valid570a922013-06-15 11:54:37 +000011087 // If FoundDecl is different from Method (such as if one is a template
11088 // and the other a specialization), make sure DiagnoseUseOfDecl is
11089 // called on both.
11090 // FIXME: This would be more comprehensively addressed by modifying
11091 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11092 // being used.
11093 if (Method != FoundDecl.getDecl() &&
11094 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11095 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000011096 break;
11097
11098 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +000011099 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +000011100 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000011101 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011102 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor88a35142008-12-22 05:46:06 +000011103 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000011104 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000011105
11106 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +000011107 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000011108 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011109 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor88a35142008-12-22 05:46:06 +000011110 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000011111 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011112
11113 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +000011114 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011115 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011116 << DeclName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011117 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011118 << MemExprE->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011119 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011120 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000011121 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000011122 }
11123
John McCall6bb80172010-03-30 21:47:33 +000011124 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +000011125
John McCallaa81e162009-12-01 22:10:20 +000011126 // If overload resolution picked a static member, build a
11127 // non-member call based on that function.
11128 if (Method->isStatic()) {
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011129 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11130 RParenLoc);
John McCallaa81e162009-12-01 22:10:20 +000011131 }
11132
John McCall129e2df2009-11-30 22:42:35 +000011133 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +000011134 }
11135
John McCallf89e55a2010-11-18 06:31:45 +000011136 QualType ResultType = Method->getResultType();
11137 ExprValueKind VK = Expr::getValueKindForType(ResultType);
11138 ResultType = ResultType.getNonLValueExprType(Context);
11139
Douglas Gregor88a35142008-12-22 05:46:06 +000011140 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011141 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011142 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCallf89e55a2010-11-18 06:31:45 +000011143 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +000011144
Anders Carlssoneed3e692009-10-10 00:06:20 +000011145 // Check for a valid return type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011146 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +000011147 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +000011148 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011149
Douglas Gregor88a35142008-12-22 05:46:06 +000011150 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +000011151 // We only need to do this if there was actually an overload; otherwise
11152 // it was done at lookup.
John Wiegley429bb272011-04-08 18:41:53 +000011153 if (!Method->isStatic()) {
11154 ExprResult ObjectArg =
11155 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11156 FoundDecl, Method);
11157 if (ObjectArg.isInvalid())
11158 return ExprError();
11159 MemExpr->setBase(ObjectArg.take());
11160 }
Douglas Gregor88a35142008-12-22 05:46:06 +000011161
11162 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +000011163 const FunctionProtoType *Proto =
11164 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011165 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor88a35142008-12-22 05:46:06 +000011166 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +000011167 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000011168
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011169 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmane61eb042012-02-18 04:48:30 +000011170
Richard Smith831421f2012-06-25 20:30:08 +000011171 if (CheckFunctionCall(Method, TheCall, Proto))
John McCallaa81e162009-12-01 22:10:20 +000011172 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +000011173
Anders Carlsson2174d4c2011-05-06 14:25:31 +000011174 if ((isa<CXXConstructorDecl>(CurContext) ||
11175 isa<CXXDestructorDecl>(CurContext)) &&
11176 TheCall->getMethodDecl()->isPure()) {
11177 const CXXMethodDecl *MD = TheCall->getMethodDecl();
11178
Chandler Carruthae198062011-06-27 08:31:58 +000011179 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson2174d4c2011-05-06 14:25:31 +000011180 Diag(MemExpr->getLocStart(),
11181 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11182 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11183 << MD->getParent()->getDeclName();
11184
11185 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruthae198062011-06-27 08:31:58 +000011186 }
Anders Carlsson2174d4c2011-05-06 14:25:31 +000011187 }
John McCall9ae2f072010-08-23 23:25:46 +000011188 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +000011189}
11190
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011191/// BuildCallToObjectOfClassType - Build a call to an object of class
11192/// type (C++ [over.call.object]), which can end up invoking an
11193/// overloaded function call operator (@c operator()) or performing a
11194/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +000011195ExprResult
John Wiegley429bb272011-04-08 18:41:53 +000011196Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregor5c37de72008-12-06 00:22:45 +000011197 SourceLocation LParenLoc,
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011198 MultiExprArg Args,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011199 SourceLocation RParenLoc) {
John McCall5acb0c92011-10-17 18:40:02 +000011200 if (checkPlaceholderForOverload(*this, Obj))
11201 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011202 ExprResult Object = Owned(Obj);
John McCall5acb0c92011-10-17 18:40:02 +000011203
11204 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011205 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall5acb0c92011-10-17 18:40:02 +000011206 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000011207
John Wiegley429bb272011-04-08 18:41:53 +000011208 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
11209 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +000011210
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011211 // C++ [over.call.object]p1:
11212 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +000011213 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011214 // candidate functions includes at least the function call
11215 // operators of T. The function call operators of T are obtained by
11216 // ordinary lookup of the name operator() in the context of
11217 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +000011218 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +000011219 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +000011220
John Wiegley429bb272011-04-08 18:41:53 +000011221 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000011222 diag::err_incomplete_object_call, Object.get()))
Douglas Gregor593564b2009-11-15 07:48:03 +000011223 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011224
John McCalla24dc2e2009-11-17 02:14:36 +000011225 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11226 LookupQualifiedName(R, Record->getDecl());
11227 R.suppressDiagnostics();
11228
Douglas Gregor593564b2009-11-15 07:48:03 +000011229 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +000011230 Oper != OperEnd; ++Oper) {
John Wiegley429bb272011-04-08 18:41:53 +000011231 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011232 Object.get()->Classify(Context),
11233 Args, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +000011234 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +000011235 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011236
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011237 // C++ [over.call.object]p2:
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011238 // In addition, for each (non-explicit in C++0x) conversion function
11239 // declared in T of the form
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011240 //
11241 // operator conversion-type-id () cv-qualifier;
11242 //
11243 // where cv-qualifier is the same cv-qualification as, or a
11244 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +000011245 // denotes the type "pointer to function of (P1,...,Pn) returning
11246 // R", or the type "reference to pointer to function of
11247 // (P1,...,Pn) returning R", or the type "reference to function
11248 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011249 // is also considered as a candidate function. Similarly,
11250 // surrogate call functions are added to the set of candidate
11251 // functions for each conversion function declared in an
11252 // accessible base class provided the function is not hidden
11253 // within T by another intervening declaration.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000011254 std::pair<CXXRecordDecl::conversion_iterator,
11255 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregor90073282010-01-11 19:36:35 +000011256 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000011257 for (CXXRecordDecl::conversion_iterator
11258 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +000011259 NamedDecl *D = *I;
11260 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11261 if (isa<UsingShadowDecl>(D))
11262 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011263
Douglas Gregor4a27d702009-10-21 06:18:39 +000011264 // Skip over templated conversion functions; they aren't
11265 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +000011266 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +000011267 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +000011268
John McCall701c89e2009-12-03 04:06:58 +000011269 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011270 if (!Conv->isExplicit()) {
11271 // Strip the reference type (if any) and then the pointer type (if
11272 // any) to get down to what might be a function type.
11273 QualType ConvType = Conv->getConversionType().getNonReferenceType();
11274 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11275 ConvType = ConvPtrType->getPointeeType();
John McCallba135432009-11-21 08:51:07 +000011276
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011277 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11278 {
11279 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011280 Object.get(), Args, CandidateSet);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011281 }
11282 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011283 }
Mike Stump1eb44332009-09-09 15:08:12 +000011284
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011285 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11286
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011287 // Perform overload resolution.
11288 OverloadCandidateSet::iterator Best;
John Wiegley429bb272011-04-08 18:41:53 +000011289 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall120d63c2010-08-24 20:38:10 +000011290 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011291 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011292 // Overload resolution succeeded; we'll build the appropriate call
11293 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011294 break;
11295
11296 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +000011297 if (CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +000011298 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley429bb272011-04-08 18:41:53 +000011299 << Object.get()->getType() << /*call*/ 1
11300 << Object.get()->getSourceRange();
John McCall1eb3e102010-01-07 02:04:15 +000011301 else
Daniel Dunbar96a00142012-03-09 18:35:03 +000011302 Diag(Object.get()->getLocStart(),
John McCall1eb3e102010-01-07 02:04:15 +000011303 diag::err_ovl_no_viable_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000011304 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011305 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011306 break;
11307
11308 case OR_Ambiguous:
Daniel Dunbar96a00142012-03-09 18:35:03 +000011309 Diag(Object.get()->getLocStart(),
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011310 diag::err_ovl_ambiguous_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000011311 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011312 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011313 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011314
11315 case OR_Deleted:
Daniel Dunbar96a00142012-03-09 18:35:03 +000011316 Diag(Object.get()->getLocStart(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011317 diag::err_ovl_deleted_object_call)
11318 << Best->Function->isDeleted()
John Wiegley429bb272011-04-08 18:41:53 +000011319 << Object.get()->getType()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011320 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley429bb272011-04-08 18:41:53 +000011321 << Object.get()->getSourceRange();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011322 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011323 break;
Mike Stump1eb44332009-09-09 15:08:12 +000011324 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011325
Douglas Gregorff331c12010-07-25 18:17:45 +000011326 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011327 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011328
John McCall5acb0c92011-10-17 18:40:02 +000011329 UnbridgedCasts.restore();
11330
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011331 if (Best->Function == 0) {
11332 // Since there is no function declaration, this is one of the
11333 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +000011334 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011335 = cast<CXXConversionDecl>(
11336 Best->Conversions[0].UserDefined.ConversionFunction);
11337
John Wiegley429bb272011-04-08 18:41:53 +000011338 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +000011339 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11340 return ExprError();
Faisal Valid570a922013-06-15 11:54:37 +000011341 assert(Conv == Best->FoundDecl.getDecl() &&
11342 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011343 // We selected one of the surrogate functions that converts the
11344 // object parameter to a function pointer. Perform the conversion
11345 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011346
Fariborz Jahaniand8307b12009-09-28 18:35:46 +000011347 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +000011348 // and then call it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011349 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11350 Conv, HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +000011351 if (Call.isInvalid())
11352 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +000011353 // Record usage of conversion in an implicit cast.
11354 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
11355 CK_UserDefinedConversion,
11356 Call.get(), 0, VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011357
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011358 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011359 }
11360
John Wiegley429bb272011-04-08 18:41:53 +000011361 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall41d89032010-01-28 01:54:34 +000011362
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011363 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11364 // that calls this method, using Object for the implicit object
11365 // parameter and passing along the remaining arguments.
11366 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Webere0ff6902012-11-09 06:06:14 +000011367
11368 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber1a52a4d2012-11-09 08:38:04 +000011369 if (Method->isInvalidDecl())
Nico Webere0ff6902012-11-09 06:06:14 +000011370 return ExprError();
11371
Chandler Carruth6df868e2010-12-12 08:17:55 +000011372 const FunctionProtoType *Proto =
11373 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011374
11375 unsigned NumArgsInProto = Proto->getNumArgs();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011376 unsigned NumArgsToCheck = Args.size();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011377
11378 // Build the full argument list for the method call (the
11379 // implicit object parameter is placed at the beginning of the
11380 // list).
11381 Expr **MethodArgs;
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011382 if (Args.size() < NumArgsInProto) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011383 NumArgsToCheck = NumArgsInProto;
11384 MethodArgs = new Expr*[NumArgsInProto + 1];
11385 } else {
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011386 MethodArgs = new Expr*[Args.size() + 1];
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011387 }
John Wiegley429bb272011-04-08 18:41:53 +000011388 MethodArgs[0] = Object.get();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011389 for (unsigned ArgIdx = 0, e = Args.size(); ArgIdx != e; ++ArgIdx)
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011390 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +000011391
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011392 DeclarationNameInfo OpLocInfo(
11393 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11394 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011395 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011396 HadMultipleCandidates,
11397 OpLocInfo.getLoc(),
11398 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000011399 if (NewFn.isInvalid())
11400 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011401
11402 // Once we've built TheCall, all of the expressions are properly
11403 // owned.
John McCallf89e55a2010-11-18 06:31:45 +000011404 QualType ResultTy = Method->getResultType();
11405 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11406 ResultTy = ResultTy.getNonLValueExprType(Context);
11407
John McCall9ae2f072010-08-23 23:25:46 +000011408 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011409 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011410 llvm::makeArrayRef(MethodArgs, Args.size()+1),
Lang Hamesbe9af122012-10-02 04:45:10 +000011411 ResultTy, VK, RParenLoc, false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011412 delete [] MethodArgs;
11413
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011414 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +000011415 Method))
11416 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011417
Douglas Gregor518fda12009-01-13 05:10:00 +000011418 // We may have default arguments. If so, we need to allocate more
11419 // slots in the call for them.
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011420 if (Args.size() < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +000011421 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011422 else if (Args.size() > NumArgsInProto)
Douglas Gregor518fda12009-01-13 05:10:00 +000011423 NumArgsToCheck = NumArgsInProto;
11424
Chris Lattner312531a2009-04-12 08:11:20 +000011425 bool IsError = false;
11426
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011427 // Initialize the implicit object parameter.
John Wiegley429bb272011-04-08 18:41:53 +000011428 ExprResult ObjRes =
11429 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11430 Best->FoundDecl, Method);
11431 if (ObjRes.isInvalid())
11432 IsError = true;
11433 else
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011434 Object = ObjRes;
John Wiegley429bb272011-04-08 18:41:53 +000011435 TheCall->setArg(0, Object.take());
Chris Lattner312531a2009-04-12 08:11:20 +000011436
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011437 // Check the argument types.
11438 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011439 Expr *Arg;
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011440 if (i < Args.size()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011441 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +000011442
Douglas Gregor518fda12009-01-13 05:10:00 +000011443 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +000011444
John McCall60d7b3a2010-08-24 06:29:42 +000011445 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +000011446 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000011447 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +000011448 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +000011449 SourceLocation(), Arg);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011450
Anders Carlsson3faa4862010-01-29 18:43:53 +000011451 IsError |= InputInit.isInvalid();
11452 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011453 } else {
John McCall60d7b3a2010-08-24 06:29:42 +000011454 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +000011455 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11456 if (DefArg.isInvalid()) {
11457 IsError = true;
11458 break;
11459 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011460
Douglas Gregord47c47d2009-11-09 19:27:57 +000011461 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011462 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011463
11464 TheCall->setArg(i + 1, Arg);
11465 }
11466
11467 // If this is a variadic call, handle args passed through "...".
11468 if (Proto->isVariadic()) {
11469 // Promote the arguments (C99 6.5.2.2p7).
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011470 for (unsigned i = NumArgsInProto, e = Args.size(); i < e; i++) {
John Wiegley429bb272011-04-08 18:41:53 +000011471 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11472 IsError |= Arg.isInvalid();
11473 TheCall->setArg(i + 1, Arg.take());
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011474 }
11475 }
11476
Chris Lattner312531a2009-04-12 08:11:20 +000011477 if (IsError) return true;
11478
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011479 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmane61eb042012-02-18 04:48:30 +000011480
Richard Smith831421f2012-06-25 20:30:08 +000011481 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +000011482 return true;
11483
John McCall182f7092010-08-24 06:09:16 +000011484 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011485}
11486
Douglas Gregor8ba10742008-11-20 16:27:02 +000011487/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +000011488/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +000011489/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +000011490ExprResult
Kaelyn Uhrainbaaeb852013-07-31 17:38:24 +000011491Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
11492 bool *NoArrowOperatorFound) {
Chandler Carruth6df868e2010-12-12 08:17:55 +000011493 assert(Base->getType()->isRecordType() &&
11494 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +000011495
John McCall5acb0c92011-10-17 18:40:02 +000011496 if (checkPlaceholderForOverload(*this, Base))
11497 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000011498
John McCall5769d612010-02-08 23:07:23 +000011499 SourceLocation Loc = Base->getExprLoc();
11500
Douglas Gregor8ba10742008-11-20 16:27:02 +000011501 // C++ [over.ref]p1:
11502 //
11503 // [...] An expression x->m is interpreted as (x.operator->())->m
11504 // for a class object x of type T if T::operator->() exists and if
11505 // the operator is selected as the best match function by the
11506 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +000011507 DeclarationName OpName =
11508 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +000011509 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +000011510 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011511
John McCall5769d612010-02-08 23:07:23 +000011512 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000011513 diag::err_typecheck_incomplete_tag, Base))
Eli Friedmanf43fb722009-11-18 01:28:03 +000011514 return ExprError();
11515
John McCalla24dc2e2009-11-17 02:14:36 +000011516 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11517 LookupQualifiedName(R, BaseRecord->getDecl());
11518 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +000011519
11520 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +000011521 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011522 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko55431692013-05-05 00:41:58 +000011523 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +000011524 }
Douglas Gregor8ba10742008-11-20 16:27:02 +000011525
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011526 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11527
Douglas Gregor8ba10742008-11-20 16:27:02 +000011528 // Perform overload resolution.
11529 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000011530 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +000011531 case OR_Success:
11532 // Overload resolution succeeded; we'll build the call below.
11533 break;
11534
11535 case OR_No_Viable_Function:
Kaelyn Uhrain45c3ba72013-07-11 22:38:30 +000011536 if (CandidateSet.empty()) {
11537 QualType BaseType = Base->getType();
Kaelyn Uhrainbaaeb852013-07-31 17:38:24 +000011538 if (NoArrowOperatorFound) {
11539 // Report this specific error to the caller instead of emitting a
11540 // diagnostic, as requested.
11541 *NoArrowOperatorFound = true;
11542 return ExprError();
11543 }
Kaelyn Uhraind4224342013-07-15 19:54:54 +000011544 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
11545 << BaseType << Base->getSourceRange();
Kaelyn Uhrain45c3ba72013-07-11 22:38:30 +000011546 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhraind4224342013-07-15 19:54:54 +000011547 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain45c3ba72013-07-11 22:38:30 +000011548 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain45c3ba72013-07-11 22:38:30 +000011549 }
11550 } else
Douglas Gregor8ba10742008-11-20 16:27:02 +000011551 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011552 << "operator->" << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011553 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011554 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011555
11556 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000011557 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11558 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011559 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011560 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011561
11562 case OR_Deleted:
11563 Diag(OpLoc, diag::err_ovl_deleted_oper)
11564 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011565 << "->"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011566 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011567 << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011568 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011569 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011570 }
11571
John McCall9aa472c2010-03-19 07:35:19 +000011572 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
11573
Douglas Gregor8ba10742008-11-20 16:27:02 +000011574 // Convert the object parameter.
11575 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000011576 ExprResult BaseResult =
11577 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11578 Best->FoundDecl, Method);
11579 if (BaseResult.isInvalid())
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011580 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011581 Base = BaseResult.take();
Douglas Gregorfc195ef2008-11-21 03:04:22 +000011582
Douglas Gregor8ba10742008-11-20 16:27:02 +000011583 // Build the operator call.
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011584 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011585 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000011586 if (FnExpr.isInvalid())
11587 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011588
John McCallf89e55a2010-11-18 06:31:45 +000011589 QualType ResultTy = Method->getResultType();
11590 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11591 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +000011592 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011593 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000011594 Base, ResultTy, VK, OpLoc, false);
Anders Carlsson15ea3782009-10-13 22:43:21 +000011595
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011596 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000011597 Method))
11598 return ExprError();
Eli Friedmand5931902011-04-04 01:18:25 +000011599
11600 return MaybeBindToTemporary(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +000011601}
11602
Richard Smith36f5cfe2012-03-09 08:00:36 +000011603/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11604/// a literal operator described by the provided lookup results.
11605ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11606 DeclarationNameInfo &SuffixInfo,
11607 ArrayRef<Expr*> Args,
11608 SourceLocation LitEndLoc,
11609 TemplateArgumentListInfo *TemplateArgs) {
11610 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smith9fcce652012-03-07 08:35:16 +000011611
Richard Smith36f5cfe2012-03-09 08:00:36 +000011612 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11613 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11614 TemplateArgs);
Richard Smith9fcce652012-03-07 08:35:16 +000011615
Richard Smith36f5cfe2012-03-09 08:00:36 +000011616 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11617
Richard Smith36f5cfe2012-03-09 08:00:36 +000011618 // Perform overload resolution. This will usually be trivial, but might need
11619 // to perform substitutions for a literal operator template.
11620 OverloadCandidateSet::iterator Best;
11621 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11622 case OR_Success:
11623 case OR_Deleted:
11624 break;
11625
11626 case OR_No_Viable_Function:
11627 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11628 << R.getLookupName();
11629 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11630 return ExprError();
11631
11632 case OR_Ambiguous:
11633 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11634 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11635 return ExprError();
Richard Smith9fcce652012-03-07 08:35:16 +000011636 }
11637
Richard Smith36f5cfe2012-03-09 08:00:36 +000011638 FunctionDecl *FD = Best->Function;
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011639 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
11640 HadMultipleCandidates,
Richard Smith36f5cfe2012-03-09 08:00:36 +000011641 SuffixInfo.getLoc(),
11642 SuffixInfo.getInfo());
11643 if (Fn.isInvalid())
11644 return true;
Richard Smith9fcce652012-03-07 08:35:16 +000011645
11646 // Check the argument types. This should almost always be a no-op, except
11647 // that array-to-pointer decay is applied to string literals.
Richard Smith9fcce652012-03-07 08:35:16 +000011648 Expr *ConvArgs[2];
Richard Smith958ba642013-05-05 15:51:06 +000011649 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smith9fcce652012-03-07 08:35:16 +000011650 ExprResult InputInit = PerformCopyInitialization(
11651 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11652 SourceLocation(), Args[ArgIdx]);
11653 if (InputInit.isInvalid())
11654 return true;
11655 ConvArgs[ArgIdx] = InputInit.take();
11656 }
11657
Richard Smith9fcce652012-03-07 08:35:16 +000011658 QualType ResultTy = FD->getResultType();
11659 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11660 ResultTy = ResultTy.getNonLValueExprType(Context);
11661
Richard Smith9fcce652012-03-07 08:35:16 +000011662 UserDefinedLiteral *UDL =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000011663 new (Context) UserDefinedLiteral(Context, Fn.take(),
11664 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smith9fcce652012-03-07 08:35:16 +000011665 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11666
11667 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11668 return ExprError();
11669
Richard Smith831421f2012-06-25 20:30:08 +000011670 if (CheckFunctionCall(FD, UDL, NULL))
Richard Smith9fcce652012-03-07 08:35:16 +000011671 return ExprError();
11672
11673 return MaybeBindToTemporary(UDL);
11674}
11675
Sam Panzere1715b62012-08-21 00:52:01 +000011676/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11677/// given LookupResult is non-empty, it is assumed to describe a member which
11678/// will be invoked. Otherwise, the function will be found via argument
11679/// dependent lookup.
11680/// CallExpr is set to a valid expression and FRS_Success returned on success,
11681/// otherwise CallExpr is set to ExprError() and some non-success value
11682/// is returned.
11683Sema::ForRangeStatus
11684Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11685 SourceLocation RangeLoc, VarDecl *Decl,
11686 BeginEndFunction BEF,
11687 const DeclarationNameInfo &NameInfo,
11688 LookupResult &MemberLookup,
11689 OverloadCandidateSet *CandidateSet,
11690 Expr *Range, ExprResult *CallExpr) {
11691 CandidateSet->clear();
11692 if (!MemberLookup.empty()) {
11693 ExprResult MemberRef =
11694 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11695 /*IsPtr=*/false, CXXScopeSpec(),
11696 /*TemplateKWLoc=*/SourceLocation(),
11697 /*FirstQualifierInScope=*/0,
11698 MemberLookup,
11699 /*TemplateArgs=*/0);
11700 if (MemberRef.isInvalid()) {
11701 *CallExpr = ExprError();
11702 Diag(Range->getLocStart(), diag::note_in_for_range)
11703 << RangeLoc << BEF << Range->getType();
11704 return FRS_DiagnosticIssued;
11705 }
Dmitri Gribenko62ed8892013-05-05 20:40:26 +000011706 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, 0);
Sam Panzere1715b62012-08-21 00:52:01 +000011707 if (CallExpr->isInvalid()) {
11708 *CallExpr = ExprError();
11709 Diag(Range->getLocStart(), diag::note_in_for_range)
11710 << RangeLoc << BEF << Range->getType();
11711 return FRS_DiagnosticIssued;
11712 }
11713 } else {
11714 UnresolvedSet<0> FoundNames;
Sam Panzere1715b62012-08-21 00:52:01 +000011715 UnresolvedLookupExpr *Fn =
11716 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11717 NestedNameSpecifierLoc(), NameInfo,
11718 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb1502bc2012-10-18 17:56:02 +000011719 FoundNames.begin(), FoundNames.end());
Sam Panzere1715b62012-08-21 00:52:01 +000011720
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011721 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzere1715b62012-08-21 00:52:01 +000011722 CandidateSet, CallExpr);
11723 if (CandidateSet->empty() || CandidateSetError) {
11724 *CallExpr = ExprError();
11725 return FRS_NoViableFunction;
11726 }
11727 OverloadCandidateSet::iterator Best;
11728 OverloadingResult OverloadResult =
11729 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
11730
11731 if (OverloadResult == OR_No_Viable_Function) {
11732 *CallExpr = ExprError();
11733 return FRS_NoViableFunction;
11734 }
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011735 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Sam Panzere1715b62012-08-21 00:52:01 +000011736 Loc, 0, CandidateSet, &Best,
11737 OverloadResult,
11738 /*AllowTypoCorrection=*/false);
11739 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
11740 *CallExpr = ExprError();
11741 Diag(Range->getLocStart(), diag::note_in_for_range)
11742 << RangeLoc << BEF << Range->getType();
11743 return FRS_DiagnosticIssued;
11744 }
11745 }
11746 return FRS_Success;
11747}
11748
11749
Douglas Gregor904eed32008-11-10 20:40:00 +000011750/// FixOverloadedFunctionReference - E is an expression that refers to
11751/// a C++ overloaded function (possibly with some parentheses and
11752/// perhaps a '&' around it). We have resolved the overloaded function
11753/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +000011754/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +000011755Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +000011756 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +000011757 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011758 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11759 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011760 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011761 return PE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011762
Douglas Gregor699ee522009-11-20 19:42:02 +000011763 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011764 }
11765
Douglas Gregor699ee522009-11-20 19:42:02 +000011766 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011767 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11768 Found, Fn);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011769 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +000011770 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +000011771 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +000011772 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +000011773 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011774 return ICE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011775
11776 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallf871d0c2010-08-07 06:22:56 +000011777 ICE->getCastKind(),
11778 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +000011779 ICE->getValueKind());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011780 }
11781
Douglas Gregor699ee522009-11-20 19:42:02 +000011782 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +000011783 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +000011784 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +000011785 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11786 if (Method->isStatic()) {
11787 // Do nothing: static member functions aren't any different
11788 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +000011789 } else {
John McCallf7a1a742009-11-24 19:00:30 +000011790 // Fix the sub expression, which really has to be an
11791 // UnresolvedLookupExpr holding an overloaded member function
11792 // or template.
John McCall6bb80172010-03-30 21:47:33 +000011793 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11794 Found, Fn);
John McCallba135432009-11-21 08:51:07 +000011795 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011796 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +000011797
John McCallba135432009-11-21 08:51:07 +000011798 assert(isa<DeclRefExpr>(SubExpr)
11799 && "fixed to something other than a decl ref");
11800 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11801 && "fixed to a member ref with no nested name qualifier");
11802
11803 // We have taken the address of a pointer to member
11804 // function. Perform the computation here so that we get the
11805 // appropriate pointer to member type.
11806 QualType ClassType
11807 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11808 QualType MemPtrType
11809 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11810
John McCallf89e55a2010-11-18 06:31:45 +000011811 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11812 VK_RValue, OK_Ordinary,
11813 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +000011814 }
11815 }
John McCall6bb80172010-03-30 21:47:33 +000011816 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11817 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011818 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011819 return UnOp;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011820
John McCall2de56d12010-08-25 11:45:40 +000011821 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +000011822 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +000011823 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +000011824 UnOp->getOperatorLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011825 }
John McCallba135432009-11-21 08:51:07 +000011826
11827 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +000011828 // FIXME: avoid copy.
11829 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +000011830 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +000011831 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11832 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +000011833 }
11834
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011835 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11836 ULE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011837 ULE->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011838 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011839 /*enclosing*/ false, // FIXME?
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011840 ULE->getNameLoc(),
11841 Fn->getType(),
11842 VK_LValue,
11843 Found.getDecl(),
11844 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011845 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011846 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11847 return DRE;
John McCallba135432009-11-21 08:51:07 +000011848 }
11849
John McCall129e2df2009-11-30 22:42:35 +000011850 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +000011851 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +000011852 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11853 if (MemExpr->hasExplicitTemplateArgs()) {
11854 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11855 TemplateArgs = &TemplateArgsBuffer;
11856 }
John McCalld5532b62009-11-23 01:53:49 +000011857
John McCallaa81e162009-12-01 22:10:20 +000011858 Expr *Base;
11859
John McCallf89e55a2010-11-18 06:31:45 +000011860 // If we're filling in a static method where we used to have an
11861 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +000011862 if (MemExpr->isImplicitAccess()) {
11863 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011864 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11865 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011866 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011867 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011868 /*enclosing*/ false,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011869 MemExpr->getMemberLoc(),
11870 Fn->getType(),
11871 VK_LValue,
11872 Found.getDecl(),
11873 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011874 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011875 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11876 return DRE;
Douglas Gregor828a1972010-01-07 23:12:05 +000011877 } else {
11878 SourceLocation Loc = MemExpr->getMemberLoc();
11879 if (MemExpr->getQualifier())
Douglas Gregor4c9be892011-02-28 20:01:57 +000011880 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman72899c32012-01-07 04:59:52 +000011881 CheckCXXThisCapture(Loc);
Douglas Gregor828a1972010-01-07 23:12:05 +000011882 Base = new (Context) CXXThisExpr(Loc,
11883 MemExpr->getBaseType(),
11884 /*isImplicit=*/true);
11885 }
John McCallaa81e162009-12-01 22:10:20 +000011886 } else
John McCall3fa5cae2010-10-26 07:05:15 +000011887 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +000011888
John McCallf5307512011-04-27 00:36:17 +000011889 ExprValueKind valueKind;
11890 QualType type;
11891 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11892 valueKind = VK_LValue;
11893 type = Fn->getType();
11894 } else {
11895 valueKind = VK_RValue;
11896 type = Context.BoundMemberTy;
11897 }
11898
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011899 MemberExpr *ME = MemberExpr::Create(Context, Base,
11900 MemExpr->isArrow(),
11901 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011902 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011903 Fn,
11904 Found,
11905 MemExpr->getMemberNameInfo(),
11906 TemplateArgs,
11907 type, valueKind, OK_Ordinary);
11908 ME->setHadMultipleCandidates(true);
Richard Smith4a030222012-11-14 07:06:31 +000011909 MarkMemberReferenced(ME);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011910 return ME;
Douglas Gregor699ee522009-11-20 19:42:02 +000011911 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011912
John McCall3fa5cae2010-10-26 07:05:15 +000011913 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregor904eed32008-11-10 20:40:00 +000011914}
11915
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011916ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCall60d7b3a2010-08-24 06:29:42 +000011917 DeclAccessPair Found,
11918 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +000011919 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +000011920}
11921
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000011922} // end namespace clang