blob: 7c34f43d270dce58f1c47d362f6259e3a3a51207 [file] [log] [blame]
Nick Lewyckye1121512013-01-24 01:12:16 +00001//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
Douglas Gregor5251f1b2008-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 Carruth3a022472012-12-04 09:13:33 +000014#include "clang/Sema/Overload.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000018#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000019#include "clang/AST/ExprCXX.h"
John McCalle26a8722010-12-04 08:14:53 +000020#include "clang/AST/ExprObjC.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Basic/Diagnostic.h"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000023#include "clang/Basic/DiagnosticOptions.h"
Anders Carlssond624e162009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
David Majnemerc729b0b2013-09-16 22:44:20 +000025#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Sema/Initialization.h"
27#include "clang/Sema/Lookup.h"
28#include "clang/Sema/SemaInternal.h"
29#include "clang/Sema/Template.h"
30#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor2bbc0262010-09-12 04:28:07 +000031#include "llvm/ADT/DenseSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "llvm/ADT/STLExtras.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000033#include "llvm/ADT/SmallPtrSet.h"
Richard Smith9ca64612012-05-07 09:03:25 +000034#include "llvm/ADT/SmallString.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000035#include <algorithm>
David Blaikie8ad22e62014-05-01 23:01:41 +000036#include <cstdlib>
Douglas Gregor5251f1b2008-10-21 16:13:35 +000037
Richard Smith17c00b42014-11-12 01:24:00 +000038using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000039using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000040
Nick Lewycky134af912013-02-07 05:08:22 +000041/// A convenience routine for creating a decayed reference to a function.
John Wiegley01296292011-04-08 18:41:53 +000042static ExprResult
Nick Lewycky134af912013-02-07 05:08:22 +000043CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
44 bool HadMultipleCandidates,
Douglas Gregore9d62932011-07-15 16:25:15 +000045 SourceLocation Loc = SourceLocation(),
46 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Richard Smith22262ab2013-05-04 06:44:46 +000047 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
Faisal Valid6676412013-06-15 11:54:37 +000048 return ExprError();
49 // If FoundDecl is different from Fn (such as if one is a template
50 // and the other a specialization), make sure DiagnoseUseOfDecl is
51 // called on both.
52 // FIXME: This would be more comprehensively addressed by modifying
53 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
54 // being used.
55 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
Richard Smith22262ab2013-05-04 06:44:46 +000056 return ExprError();
John McCall113bee02012-03-10 09:33:50 +000057 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000058 VK_LValue, Loc, LocInfo);
59 if (HadMultipleCandidates)
60 DRE->setHadMultipleCandidates(true);
Nick Lewycky134af912013-02-07 05:08:22 +000061
62 S.MarkDeclRefReferenced(DRE);
Nick Lewycky134af912013-02-07 05:08:22 +000063
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000064 ExprResult E = DRE;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000065 E = S.DefaultFunctionArrayConversion(E.get());
John Wiegley01296292011-04-08 18:41:53 +000066 if (E.isInvalid())
67 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +000068 return E;
John McCall7decc9e2010-11-18 06:31:45 +000069}
70
John McCall5c32be02010-08-24 20:38:10 +000071static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
72 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000073 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000074 bool CStyle,
75 bool AllowObjCWritebackConversion);
Sam Panzer04390a62012-08-16 02:38:47 +000076
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000077static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
78 QualType &ToType,
79 bool InOverloadResolution,
80 StandardConversionSequence &SCS,
81 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000082static OverloadingResult
83IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
84 UserDefinedConversionSequence& User,
85 OverloadCandidateSet& Conversions,
Douglas Gregor4b60a152013-11-07 22:34:54 +000086 bool AllowExplicit,
87 bool AllowObjCConversionOnExplicit);
John McCall5c32be02010-08-24 20:38:10 +000088
89
90static ImplicitConversionSequence::CompareKind
91CompareStandardConversionSequences(Sema &S,
92 const StandardConversionSequence& SCS1,
93 const StandardConversionSequence& SCS2);
94
95static ImplicitConversionSequence::CompareKind
96CompareQualificationConversions(Sema &S,
97 const StandardConversionSequence& SCS1,
98 const StandardConversionSequence& SCS2);
99
100static ImplicitConversionSequence::CompareKind
101CompareDerivedToBaseConversions(Sema &S,
102 const StandardConversionSequence& SCS1,
103 const StandardConversionSequence& SCS2);
104
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000105/// GetConversionRank - Retrieve the implicit conversion rank
106/// corresponding to the given implicit conversion kind.
Richard Smith17c00b42014-11-12 01:24:00 +0000107ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000108 static const ImplicitConversionRank
109 Rank[(int)ICK_Num_Conversion_Kinds] = {
110 ICR_Exact_Match,
111 ICR_Exact_Match,
112 ICR_Exact_Match,
113 ICR_Exact_Match,
114 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000115 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000116 ICR_Promotion,
117 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000118 ICR_Promotion,
119 ICR_Conversion,
120 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000121 ICR_Conversion,
122 ICR_Conversion,
123 ICR_Conversion,
124 ICR_Conversion,
125 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000126 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000127 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000128 ICR_Conversion,
129 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000130 ICR_Complex_Real_Conversion,
131 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000132 ICR_Conversion,
133 ICR_Writeback_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000134 };
135 return Rank[(int)Kind];
136}
137
138/// GetImplicitConversionName - Return the name of this kind of
139/// implicit conversion.
Richard Smith17c00b42014-11-12 01:24:00 +0000140static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000141 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000142 "No conversion",
143 "Lvalue-to-rvalue",
144 "Array-to-pointer",
145 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000146 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000147 "Qualification",
148 "Integral promotion",
149 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000150 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000151 "Integral conversion",
152 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000153 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000154 "Floating-integral conversion",
155 "Pointer conversion",
156 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000157 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000158 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000159 "Derived-to-base conversion",
160 "Vector conversion",
161 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000162 "Complex-real conversion",
163 "Block Pointer conversion",
Sylvestre Ledru55635ce2014-11-17 19:41:49 +0000164 "Transparent Union Conversion",
John McCall31168b02011-06-15 23:02:42 +0000165 "Writeback conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000166 };
167 return Name[Kind];
168}
169
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000170/// StandardConversionSequence - Set the standard conversion
171/// sequence to the identity conversion.
172void StandardConversionSequence::setAsIdentityConversion() {
173 First = ICK_Identity;
174 Second = ICK_Identity;
175 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000176 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000177 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000178 ReferenceBinding = false;
179 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000180 IsLvalueReference = true;
181 BindsToFunctionLvalue = false;
182 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000183 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000184 ObjCLifetimeConversionBinding = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000185 CopyConstructor = nullptr;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000186}
187
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000188/// getRank - Retrieve the rank of this standard conversion sequence
189/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
190/// implicit conversions.
191ImplicitConversionRank StandardConversionSequence::getRank() const {
192 ImplicitConversionRank Rank = ICR_Exact_Match;
193 if (GetConversionRank(First) > Rank)
194 Rank = GetConversionRank(First);
195 if (GetConversionRank(Second) > Rank)
196 Rank = GetConversionRank(Second);
197 if (GetConversionRank(Third) > Rank)
198 Rank = GetConversionRank(Third);
199 return Rank;
200}
201
202/// isPointerConversionToBool - Determines whether this conversion is
203/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000204/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000205/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000206bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000207 // Note that FromType has not necessarily been transformed by the
208 // array-to-pointer or function-to-pointer implicit conversions, so
209 // check for their presence as well as checking whether FromType is
210 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000211 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000212 (getFromType()->isPointerType() ||
213 getFromType()->isObjCObjectPointerType() ||
214 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000215 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000216 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
217 return true;
218
219 return false;
220}
221
Douglas Gregor5c407d92008-10-23 00:40:37 +0000222/// isPointerConversionToVoidPointer - Determines whether this
223/// conversion is a conversion of a pointer to a void pointer. This is
224/// used as part of the ranking of standard conversion sequences (C++
225/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000226bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000227StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000228isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000229 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000230 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000231
232 // Note that FromType has not necessarily been transformed by the
233 // array-to-pointer implicit conversion, so check for its presence
234 // and redo the conversion to get a pointer.
235 if (First == ICK_Array_To_Pointer)
236 FromType = Context.getArrayDecayedType(FromType);
237
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000238 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000239 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000240 return ToPtrType->getPointeeType()->isVoidType();
241
242 return false;
243}
244
Richard Smith66e05fe2012-01-18 05:21:49 +0000245/// Skip any implicit casts which could be either part of a narrowing conversion
246/// or after one in an implicit conversion.
247static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
248 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
249 switch (ICE->getCastKind()) {
250 case CK_NoOp:
251 case CK_IntegralCast:
252 case CK_IntegralToBoolean:
253 case CK_IntegralToFloating:
254 case CK_FloatingToIntegral:
255 case CK_FloatingToBoolean:
256 case CK_FloatingCast:
257 Converted = ICE->getSubExpr();
258 continue;
259
260 default:
261 return Converted;
262 }
263 }
264
265 return Converted;
266}
267
268/// Check if this standard conversion sequence represents a narrowing
269/// conversion, according to C++11 [dcl.init.list]p7.
270///
271/// \param Ctx The AST context.
272/// \param Converted The result of applying this standard conversion sequence.
273/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
274/// value of the expression prior to the narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000275/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
276/// type of the expression prior to the narrowing conversion.
Richard Smith66e05fe2012-01-18 05:21:49 +0000277NarrowingKind
Richard Smithf8379a02012-01-18 23:55:52 +0000278StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
279 const Expr *Converted,
Richard Smith5614ca72012-03-23 23:55:39 +0000280 APValue &ConstantValue,
281 QualType &ConstantType) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000282 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-01-18 05:21:49 +0000283
284 // C++11 [dcl.init.list]p7:
285 // A narrowing conversion is an implicit conversion ...
286 QualType FromType = getToType(0);
287 QualType ToType = getToType(1);
288 switch (Second) {
289 // -- from a floating-point type to an integer type, or
290 //
291 // -- from an integer type or unscoped enumeration type to a floating-point
292 // type, except where the source is a constant expression and the actual
293 // value after conversion will fit into the target type and will produce
294 // the original value when converted back to the original type, or
295 case ICK_Floating_Integral:
296 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
297 return NK_Type_Narrowing;
298 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
299 llvm::APSInt IntConstantValue;
300 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
301 if (Initializer &&
302 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
303 // Convert the integer to the floating type.
304 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
305 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
306 llvm::APFloat::rmNearestTiesToEven);
307 // And back.
308 llvm::APSInt ConvertedValue = IntConstantValue;
309 bool ignored;
310 Result.convertToInteger(ConvertedValue,
311 llvm::APFloat::rmTowardZero, &ignored);
312 // If the resulting value is different, this was a narrowing conversion.
313 if (IntConstantValue != ConvertedValue) {
314 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000315 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000316 return NK_Constant_Narrowing;
317 }
318 } else {
319 // Variables are always narrowings.
320 return NK_Variable_Narrowing;
321 }
322 }
323 return NK_Not_Narrowing;
324
325 // -- from long double to double or float, or from double to float, except
326 // where the source is a constant expression and the actual value after
327 // conversion is within the range of values that can be represented (even
328 // if it cannot be represented exactly), or
329 case ICK_Floating_Conversion:
330 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
331 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
332 // FromType is larger than ToType.
333 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
334 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
335 // Constant!
336 assert(ConstantValue.isFloat());
337 llvm::APFloat FloatVal = ConstantValue.getFloat();
338 // Convert the source value into the target type.
339 bool ignored;
340 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
341 Ctx.getFloatTypeSemantics(ToType),
342 llvm::APFloat::rmNearestTiesToEven, &ignored);
343 // If there was no overflow, the source value is within the range of
344 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000345 if (ConvertStatus & llvm::APFloat::opOverflow) {
346 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000347 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000348 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000349 } else {
350 return NK_Variable_Narrowing;
351 }
352 }
353 return NK_Not_Narrowing;
354
355 // -- from an integer type or unscoped enumeration type to an integer type
356 // that cannot represent all the values of the original type, except where
357 // the source is a constant expression and the actual value after
358 // conversion will fit into the target type and will produce the original
359 // value when converted back to the original type.
360 case ICK_Boolean_Conversion: // Bools are integers too.
361 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
362 // Boolean conversions can be from pointers and pointers to members
363 // [conv.bool], and those aren't considered narrowing conversions.
364 return NK_Not_Narrowing;
365 } // Otherwise, fall through to the integral case.
366 case ICK_Integral_Conversion: {
367 assert(FromType->isIntegralOrUnscopedEnumerationType());
368 assert(ToType->isIntegralOrUnscopedEnumerationType());
369 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
370 const unsigned FromWidth = Ctx.getIntWidth(FromType);
371 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
372 const unsigned ToWidth = Ctx.getIntWidth(ToType);
373
374 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000375 (FromWidth == ToWidth && FromSigned != ToSigned) ||
376 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000377 // Not all values of FromType can be represented in ToType.
378 llvm::APSInt InitializerValue;
379 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith25a80d42012-06-13 01:07:41 +0000380 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
381 // Such conversions on variables are always narrowing.
382 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000383 }
384 bool Narrowing = false;
385 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000386 // Negative -> unsigned is narrowing. Otherwise, more bits is never
387 // narrowing.
388 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000389 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000390 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000391 // Add a bit to the InitializerValue so we don't have to worry about
392 // signed vs. unsigned comparisons.
393 InitializerValue = InitializerValue.extend(
394 InitializerValue.getBitWidth() + 1);
395 // Convert the initializer to and from the target width and signed-ness.
396 llvm::APSInt ConvertedValue = InitializerValue;
397 ConvertedValue = ConvertedValue.trunc(ToWidth);
398 ConvertedValue.setIsSigned(ToSigned);
399 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
400 ConvertedValue.setIsSigned(InitializerValue.isSigned());
401 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000402 if (ConvertedValue != InitializerValue)
403 Narrowing = true;
404 }
405 if (Narrowing) {
406 ConstantType = Initializer->getType();
407 ConstantValue = APValue(InitializerValue);
408 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000409 }
410 }
411 return NK_Not_Narrowing;
412 }
413
414 default:
415 // Other kinds of conversions are not narrowings.
416 return NK_Not_Narrowing;
417 }
418}
419
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000420/// dump - Print this standard conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000421/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000422void StandardConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000423 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000424 bool PrintedSomething = false;
425 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000426 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000427 PrintedSomething = true;
428 }
429
430 if (Second != ICK_Identity) {
431 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000432 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000433 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000434 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000435
436 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000437 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000438 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000439 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000440 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000441 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000442 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000443 PrintedSomething = true;
444 }
445
446 if (Third != ICK_Identity) {
447 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000448 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000449 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000450 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000451 PrintedSomething = true;
452 }
453
454 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000455 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000456 }
457}
458
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000459/// dump - Print this user-defined conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000460/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000461void UserDefinedConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000462 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000463 if (Before.First || Before.Second || Before.Third) {
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000464 Before.dump();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000465 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000466 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000467 if (ConversionFunction)
468 OS << '\'' << *ConversionFunction << '\'';
469 else
470 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000471 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000472 OS << " -> ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000473 After.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000474 }
475}
476
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000477/// dump - Print this implicit conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000478/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000479void ImplicitConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000480 raw_ostream &OS = llvm::errs();
Richard Smitha93f1022013-09-06 22:30:28 +0000481 if (isStdInitializerListElement())
482 OS << "Worst std::initializer_list element conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000483 switch (ConversionKind) {
484 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000485 OS << "Standard conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000486 Standard.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000487 break;
488 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000489 OS << "User-defined conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000490 UserDefined.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000491 break;
492 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000493 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000494 break;
John McCall0d1da222010-01-12 00:44:57 +0000495 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000496 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000497 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000498 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000499 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000500 break;
501 }
502
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000503 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000504}
505
John McCall0d1da222010-01-12 00:44:57 +0000506void AmbiguousConversionSequence::construct() {
507 new (&conversions()) ConversionSet();
508}
509
510void AmbiguousConversionSequence::destruct() {
511 conversions().~ConversionSet();
512}
513
514void
515AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
516 FromTypePtr = O.FromTypePtr;
517 ToTypePtr = O.ToTypePtr;
518 new (&conversions()) ConversionSet(O.conversions());
519}
520
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000521namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000522 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000523 // template argument information.
524 struct DFIArguments {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000525 TemplateArgument FirstArg;
526 TemplateArgument SecondArg;
527 };
Larisse Voufo98b20f12013-07-19 23:00:19 +0000528 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000529 // template parameter and template argument information.
530 struct DFIParamWithArguments : DFIArguments {
531 TemplateParameter Param;
532 };
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000533}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000534
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000535/// \brief Convert from Sema's representation of template deduction information
536/// to the form used in overload-candidate information.
Richard Smith17c00b42014-11-12 01:24:00 +0000537DeductionFailureInfo
538clang::MakeDeductionFailureInfo(ASTContext &Context,
539 Sema::TemplateDeductionResult TDK,
540 TemplateDeductionInfo &Info) {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000541 DeductionFailureInfo Result;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000542 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000543 Result.HasDiagnostic = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000544 Result.Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000545 switch (TDK) {
546 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000547 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000548 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000549 case Sema::TDK_TooManyArguments:
550 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000551 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000552
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000553 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000554 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000555 Result.Data = Info.Param.getOpaqueValue();
556 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000557
Richard Smith44ecdbd2013-01-31 05:19:49 +0000558 case Sema::TDK_NonDeducedMismatch: {
559 // FIXME: Should allocate from normal heap so that we can free this later.
560 DFIArguments *Saved = new (Context) DFIArguments;
561 Saved->FirstArg = Info.FirstArg;
562 Saved->SecondArg = Info.SecondArg;
563 Result.Data = Saved;
564 break;
565 }
566
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000567 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000568 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000569 // FIXME: Should allocate from normal heap so that we can free this later.
570 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000571 Saved->Param = Info.Param;
572 Saved->FirstArg = Info.FirstArg;
573 Saved->SecondArg = Info.SecondArg;
574 Result.Data = Saved;
575 break;
576 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000577
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000578 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000579 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000580 if (Info.hasSFINAEDiagnostic()) {
581 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
582 SourceLocation(), PartialDiagnostic::NullDiagnostic());
583 Info.takeSFINAEDiagnostic(*Diag);
584 Result.HasDiagnostic = true;
585 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000586 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000587
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000588 case Sema::TDK_FailedOverloadResolution:
Richard Smith8c6eeb92013-01-31 04:03:12 +0000589 Result.Data = Info.Expression;
590 break;
591
Richard Smith44ecdbd2013-01-31 05:19:49 +0000592 case Sema::TDK_MiscellaneousDeductionFailure:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000593 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000594 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000595
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000596 return Result;
597}
John McCall0d1da222010-01-12 00:44:57 +0000598
Larisse Voufo98b20f12013-07-19 23:00:19 +0000599void DeductionFailureInfo::Destroy() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000600 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
601 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000602 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000603 case Sema::TDK_InstantiationDepth:
604 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000605 case Sema::TDK_TooManyArguments:
606 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000607 case Sema::TDK_InvalidExplicitArguments:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000608 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000609 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000610
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000611 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000612 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000613 case Sema::TDK_NonDeducedMismatch:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000614 // FIXME: Destroy the data?
Craig Topperc3ec1492014-05-26 06:22:03 +0000615 Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000616 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000617
618 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000619 // FIXME: Destroy the template argument list?
Craig Topperc3ec1492014-05-26 06:22:03 +0000620 Data = nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000621 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
622 Diag->~PartialDiagnosticAt();
623 HasDiagnostic = false;
624 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000625 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000626
Douglas Gregor461761d2010-05-08 18:20:53 +0000627 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000628 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000629 break;
630 }
631}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000632
Larisse Voufo98b20f12013-07-19 23:00:19 +0000633PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smith9ca64612012-05-07 09:03:25 +0000634 if (HasDiagnostic)
635 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
Craig Topperc3ec1492014-05-26 06:22:03 +0000636 return nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000637}
638
Larisse Voufo98b20f12013-07-19 23:00:19 +0000639TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000640 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
641 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000642 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000643 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000644 case Sema::TDK_TooManyArguments:
645 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000646 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000647 case Sema::TDK_NonDeducedMismatch:
648 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000649 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000650
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000651 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000652 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000653 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000654
655 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000656 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000657 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000658
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000659 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000660 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000661 break;
662 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000663
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000664 return TemplateParameter();
665}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000666
Larisse Voufo98b20f12013-07-19 23:00:19 +0000667TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregord09efd42010-05-08 20:07:26 +0000668 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith44ecdbd2013-01-31 05:19:49 +0000669 case Sema::TDK_Success:
670 case Sema::TDK_Invalid:
671 case Sema::TDK_InstantiationDepth:
672 case Sema::TDK_TooManyArguments:
673 case Sema::TDK_TooFewArguments:
674 case Sema::TDK_Incomplete:
675 case Sema::TDK_InvalidExplicitArguments:
676 case Sema::TDK_Inconsistent:
677 case Sema::TDK_Underqualified:
678 case Sema::TDK_NonDeducedMismatch:
679 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000680 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000681
Richard Smith44ecdbd2013-01-31 05:19:49 +0000682 case Sema::TDK_SubstitutionFailure:
683 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000684
Richard Smith44ecdbd2013-01-31 05:19:49 +0000685 // Unhandled
686 case Sema::TDK_MiscellaneousDeductionFailure:
687 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000688 }
689
Craig Topperc3ec1492014-05-26 06:22:03 +0000690 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000691}
692
Larisse Voufo98b20f12013-07-19 23:00:19 +0000693const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000694 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
695 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000696 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000697 case Sema::TDK_InstantiationDepth:
698 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000699 case Sema::TDK_TooManyArguments:
700 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000701 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000702 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000703 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000704 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000705
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000706 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000707 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000708 case Sema::TDK_NonDeducedMismatch:
709 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000710
Douglas Gregor461761d2010-05-08 18:20:53 +0000711 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000712 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000713 break;
714 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000715
Craig Topperc3ec1492014-05-26 06:22:03 +0000716 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000717}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000718
Larisse Voufo98b20f12013-07-19 23:00:19 +0000719const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000720 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
721 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000722 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000723 case Sema::TDK_InstantiationDepth:
724 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000725 case Sema::TDK_TooManyArguments:
726 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000727 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000728 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000729 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000730 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000731
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000732 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000733 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000734 case Sema::TDK_NonDeducedMismatch:
735 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000736
Douglas Gregor461761d2010-05-08 18:20:53 +0000737 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000738 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000739 break;
740 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000741
Craig Topperc3ec1492014-05-26 06:22:03 +0000742 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000743}
744
Larisse Voufo98b20f12013-07-19 23:00:19 +0000745Expr *DeductionFailureInfo::getExpr() {
Richard Smith8c6eeb92013-01-31 04:03:12 +0000746 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
747 Sema::TDK_FailedOverloadResolution)
748 return static_cast<Expr*>(Data);
749
Craig Topperc3ec1492014-05-26 06:22:03 +0000750 return nullptr;
Richard Smith8c6eeb92013-01-31 04:03:12 +0000751}
752
Benjamin Kramer97e59492012-10-09 15:52:25 +0000753void OverloadCandidateSet::destroyCandidates() {
Richard Smith0bf93aa2012-07-18 23:52:59 +0000754 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer02b08432012-01-14 20:16:52 +0000755 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
756 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smith0bf93aa2012-07-18 23:52:59 +0000757 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
758 i->DeductionFailure.Destroy();
759 }
Benjamin Kramer97e59492012-10-09 15:52:25 +0000760}
761
762void OverloadCandidateSet::clear() {
763 destroyCandidates();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000764 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000765 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000766 Functions.clear();
767}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000768
John McCall4124c492011-10-17 18:40:02 +0000769namespace {
770 class UnbridgedCastsSet {
771 struct Entry {
772 Expr **Addr;
773 Expr *Saved;
774 };
775 SmallVector<Entry, 2> Entries;
776
777 public:
778 void save(Sema &S, Expr *&E) {
779 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
780 Entry entry = { &E, E };
781 Entries.push_back(entry);
782 E = S.stripARCUnbridgedCast(E);
783 }
784
785 void restore() {
786 for (SmallVectorImpl<Entry>::iterator
787 i = Entries.begin(), e = Entries.end(); i != e; ++i)
788 *i->Addr = i->Saved;
789 }
790 };
791}
792
793/// checkPlaceholderForOverload - Do any interesting placeholder-like
794/// preprocessing on the given expression.
795///
796/// \param unbridgedCasts a collection to which to add unbridged casts;
797/// without this, they will be immediately diagnosed as errors
798///
799/// Return true on unrecoverable error.
Craig Topperc3ec1492014-05-26 06:22:03 +0000800static bool
801checkPlaceholderForOverload(Sema &S, Expr *&E,
802 UnbridgedCastsSet *unbridgedCasts = nullptr) {
John McCall4124c492011-10-17 18:40:02 +0000803 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
804 // We can't handle overloaded expressions here because overload
805 // resolution might reasonably tweak them.
806 if (placeholder->getKind() == BuiltinType::Overload) return false;
807
808 // If the context potentially accepts unbridged ARC casts, strip
809 // the unbridged cast and add it to the collection for later restoration.
810 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
811 unbridgedCasts) {
812 unbridgedCasts->save(S, E);
813 return false;
814 }
815
816 // Go ahead and check everything else.
817 ExprResult result = S.CheckPlaceholderExpr(E);
818 if (result.isInvalid())
819 return true;
820
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000821 E = result.get();
John McCall4124c492011-10-17 18:40:02 +0000822 return false;
823 }
824
825 // Nothing to do.
826 return false;
827}
828
829/// checkArgPlaceholdersForOverload - Check a set of call operands for
830/// placeholders.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000831static bool checkArgPlaceholdersForOverload(Sema &S,
832 MultiExprArg Args,
John McCall4124c492011-10-17 18:40:02 +0000833 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000834 for (unsigned i = 0, e = Args.size(); i != e; ++i)
835 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall4124c492011-10-17 18:40:02 +0000836 return true;
837
838 return false;
839}
840
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000841// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000842// overload of the declarations in Old. This routine returns false if
843// New and Old cannot be overloaded, e.g., if New has the same
844// signature as some function in Old (C++ 1.3.10) or if the Old
845// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000846// it does return false, MatchedDecl will point to the decl that New
847// cannot be overloaded with. This decl may be a UsingShadowDecl on
848// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000849//
850// Example: Given the following input:
851//
852// void f(int, float); // #1
853// void f(int, int); // #2
854// int f(int, int); // #3
855//
856// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000857// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000858//
John McCall3d988d92009-12-02 08:47:38 +0000859// When we process #2, Old contains only the FunctionDecl for #1. By
860// comparing the parameter types, we see that #1 and #2 are overloaded
861// (since they have different signatures), so this routine returns
862// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000863//
John McCall3d988d92009-12-02 08:47:38 +0000864// When we process #3, Old is an overload set containing #1 and #2. We
865// compare the signatures of #3 to #1 (they're overloaded, so we do
866// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
867// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000868// signature), IsOverload returns false and MatchedDecl will be set to
869// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000870//
871// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
872// into a class by a using declaration. The rules for whether to hide
873// shadow declarations ignore some properties which otherwise figure
874// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000875Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000876Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
877 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000878 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000879 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000880 NamedDecl *OldD = *I;
881
882 bool OldIsUsingDecl = false;
883 if (isa<UsingShadowDecl>(OldD)) {
884 OldIsUsingDecl = true;
885
886 // We can always introduce two using declarations into the same
887 // context, even if they have identical signatures.
888 if (NewIsUsingDecl) continue;
889
890 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
891 }
892
893 // If either declaration was introduced by a using declaration,
894 // we'll need to use slightly different rules for matching.
895 // Essentially, these rules are the normal rules, except that
896 // function templates hide function templates with different
897 // return types or template parameter lists.
898 bool UseMemberUsingDeclRules =
John McCallc70fca62013-04-03 21:19:47 +0000899 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
900 !New->getFriendObjectKind();
John McCalle9cccd82010-06-16 08:42:20 +0000901
Alp Tokera2794f92014-01-22 07:29:52 +0000902 if (FunctionDecl *OldF = OldD->getAsFunction()) {
John McCalle9cccd82010-06-16 08:42:20 +0000903 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
904 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
905 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
906 continue;
907 }
908
Alp Tokera2794f92014-01-22 07:29:52 +0000909 if (!isa<FunctionTemplateDecl>(OldD) &&
910 !shouldLinkPossiblyHiddenDecl(*I, New))
Rafael Espindola5bddd6a2013-04-15 12:49:13 +0000911 continue;
912
John McCalldaa3d6b2009-12-09 03:35:25 +0000913 Match = *I;
914 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000915 }
John McCalla8987a2942010-11-10 03:01:53 +0000916 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000917 // We can overload with these, which can show up when doing
918 // redeclaration checks for UsingDecls.
919 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000920 } else if (isa<TagDecl>(OldD)) {
921 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000922 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
923 // Optimistically assume that an unresolved using decl will
924 // overload; if it doesn't, we'll have to diagnose during
925 // template instantiation.
926 } else {
John McCall1f82f242009-11-18 22:49:29 +0000927 // (C++ 13p1):
928 // Only function declarations can be overloaded; object and type
929 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000930 Match = *I;
931 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000932 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000933 }
John McCall1f82f242009-11-18 22:49:29 +0000934
John McCalldaa3d6b2009-12-09 03:35:25 +0000935 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000936}
937
Richard Smithac974a32013-06-30 09:48:50 +0000938bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
939 bool UseUsingDeclRules) {
940 // C++ [basic.start.main]p2: This function shall not be overloaded.
941 if (New->isMain())
Rafael Espindola576127d2012-12-28 14:21:58 +0000942 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +0000943
David Majnemerc729b0b2013-09-16 22:44:20 +0000944 // MSVCRT user defined entry points cannot be overloaded.
945 if (New->isMSVCRTEntryPoint())
946 return false;
947
John McCall1f82f242009-11-18 22:49:29 +0000948 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
949 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
950
951 // C++ [temp.fct]p2:
952 // A function template can be overloaded with other function templates
953 // and with normal (non-template) functions.
Craig Topperc3ec1492014-05-26 06:22:03 +0000954 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
John McCall1f82f242009-11-18 22:49:29 +0000955 return true;
956
957 // Is the function New an overload of the function Old?
Richard Smithac974a32013-06-30 09:48:50 +0000958 QualType OldQType = Context.getCanonicalType(Old->getType());
959 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall1f82f242009-11-18 22:49:29 +0000960
961 // Compare the signatures (C++ 1.3.10) of the two functions to
962 // determine whether they are overloads. If we find any mismatch
963 // in the signature, they are overloads.
964
965 // If either of these functions is a K&R-style function (no
966 // prototype), then we consider them to have matching signatures.
967 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
968 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
969 return false;
970
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000971 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
972 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000973
974 // The signature of a function includes the types of its
975 // parameters (C++ 1.3.10), which includes the presence or absence
976 // of the ellipsis; see C++ DR 357).
977 if (OldQType != NewQType &&
Alp Toker9cacbab2014-01-20 20:26:09 +0000978 (OldType->getNumParams() != NewType->getNumParams() ||
John McCall1f82f242009-11-18 22:49:29 +0000979 OldType->isVariadic() != NewType->isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +0000980 !FunctionParamTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000981 return true;
982
983 // C++ [temp.over.link]p4:
984 // The signature of a function template consists of its function
985 // signature, its return type and its template parameter list. The names
986 // of the template parameters are significant only for establishing the
987 // relationship between the template parameters and the rest of the
988 // signature.
989 //
990 // We check the return type and template parameter lists for function
991 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000992 //
993 // However, we don't consider either of these when deciding whether
994 // a member introduced by a shadow declaration is hidden.
995 if (!UseUsingDeclRules && NewTemplate &&
Richard Smithac974a32013-06-30 09:48:50 +0000996 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
997 OldTemplate->getTemplateParameters(),
998 false, TPL_TemplateMatch) ||
Alp Toker314cc812014-01-25 16:55:45 +0000999 OldType->getReturnType() != NewType->getReturnType()))
John McCall1f82f242009-11-18 22:49:29 +00001000 return true;
1001
1002 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001003 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001004 //
1005 // As part of this, also check whether one of the member functions
1006 // is static, in which case they are not overloads (C++
1007 // 13.1p2). While not part of the definition of the signature,
1008 // this check is important to determine whether these functions
1009 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001010 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1011 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001012 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001013 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1014 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1015 if (!UseUsingDeclRules &&
1016 (OldMethod->getRefQualifier() == RQ_None ||
1017 NewMethod->getRefQualifier() == RQ_None)) {
1018 // C++0x [over.load]p2:
1019 // - Member function declarations with the same name and the same
1020 // parameter-type-list as well as member function template
1021 // declarations with the same name, the same parameter-type-list, and
1022 // the same template parameter lists cannot be overloaded if any of
1023 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001024 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001025 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001026 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001027 }
1028 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001029 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001030
Richard Smith574f4f62013-01-14 05:37:29 +00001031 // We may not have applied the implicit const for a constexpr member
1032 // function yet (because we haven't yet resolved whether this is a static
1033 // or non-static member function). Add it now, on the assumption that this
1034 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001035 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001036 unsigned NewQuals = NewMethod->getTypeQualifiers();
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001037 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001038 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001039 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001040
1041 // We do not allow overloading based off of '__restrict'.
1042 OldQuals &= ~Qualifiers::Restrict;
1043 NewQuals &= ~Qualifiers::Restrict;
1044 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001045 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001046 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001047
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001048 // enable_if attributes are an order-sensitive part of the signature.
1049 for (specific_attr_iterator<EnableIfAttr>
1050 NewI = New->specific_attr_begin<EnableIfAttr>(),
1051 NewE = New->specific_attr_end<EnableIfAttr>(),
1052 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1053 OldE = Old->specific_attr_end<EnableIfAttr>();
1054 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1055 if (NewI == NewE || OldI == OldE)
1056 return true;
1057 llvm::FoldingSetNodeID NewID, OldID;
1058 NewI->getCond()->Profile(NewID, Context, true);
1059 OldI->getCond()->Profile(OldID, Context, true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00001060 if (NewID != OldID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001061 return true;
1062 }
1063
John McCall1f82f242009-11-18 22:49:29 +00001064 // The signatures match; this is not an overload.
1065 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001066}
1067
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001068/// \brief Checks availability of the function depending on the current
1069/// function context. Inside an unavailable function, unavailability is ignored.
1070///
1071/// \returns true if \arg FD is unavailable and current context is inside
1072/// an available function, false otherwise.
1073bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1074 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1075}
1076
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001077/// \brief Tries a user-defined conversion from From to ToType.
1078///
1079/// Produces an implicit conversion sequence for when a standard conversion
1080/// is not an option. See TryImplicitConversion for more information.
1081static ImplicitConversionSequence
1082TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1083 bool SuppressUserConversions,
1084 bool AllowExplicit,
1085 bool InOverloadResolution,
1086 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001087 bool AllowObjCWritebackConversion,
1088 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001089 ImplicitConversionSequence ICS;
1090
1091 if (SuppressUserConversions) {
1092 // We're not in the case above, so there is no conversion that
1093 // we can perform.
1094 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1095 return ICS;
1096 }
1097
1098 // Attempt user-defined conversion.
Richard Smith100b24a2014-04-17 01:52:14 +00001099 OverloadCandidateSet Conversions(From->getExprLoc(),
1100 OverloadCandidateSet::CSK_Normal);
Richard Smith48372b62015-01-27 03:30:40 +00001101 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1102 Conversions, AllowExplicit,
1103 AllowObjCConversionOnExplicit)) {
1104 case OR_Success:
1105 case OR_Deleted:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001106 ICS.setUserDefined();
Ismail Pazarbasidf1a2802014-01-24 13:16:17 +00001107 ICS.UserDefined.Before.setAsIdentityConversion();
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001108 // C++ [over.ics.user]p4:
1109 // A conversion of an expression of class type to the same class
1110 // type is given Exact Match rank, and a conversion of an
1111 // expression of class type to a base class of that type is
1112 // given Conversion rank, in spite of the fact that a copy
1113 // constructor (i.e., a user-defined conversion function) is
1114 // called for those cases.
1115 if (CXXConstructorDecl *Constructor
1116 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1117 QualType FromCanon
1118 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1119 QualType ToCanon
1120 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1121 if (Constructor->isCopyConstructor() &&
1122 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1123 // Turn this into a "standard" conversion sequence, so that it
1124 // gets ranked with standard conversion sequences.
1125 ICS.setStandard();
1126 ICS.Standard.setAsIdentityConversion();
1127 ICS.Standard.setFromType(From->getType());
1128 ICS.Standard.setAllToTypes(ToType);
1129 ICS.Standard.CopyConstructor = Constructor;
1130 if (ToCanon != FromCanon)
1131 ICS.Standard.Second = ICK_Derived_To_Base;
1132 }
1133 }
Richard Smith48372b62015-01-27 03:30:40 +00001134 break;
1135
1136 case OR_Ambiguous:
1137 if (!SuppressUserConversions) {
1138 ICS.setAmbiguous();
1139 ICS.Ambiguous.setFromType(From->getType());
1140 ICS.Ambiguous.setToType(ToType);
1141 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1142 Cand != Conversions.end(); ++Cand)
1143 if (Cand->Viable)
1144 ICS.Ambiguous.addConversion(Cand->Function);
1145 break;
1146 }
1147
1148 // Fall through.
1149 case OR_No_Viable_Function:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001150 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Richard Smith48372b62015-01-27 03:30:40 +00001151 break;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001152 }
1153
1154 return ICS;
1155}
1156
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001157/// TryImplicitConversion - Attempt to perform an implicit conversion
1158/// from the given expression (Expr) to the given type (ToType). This
1159/// function returns an implicit conversion sequence that can be used
1160/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001161///
1162/// void f(float f);
1163/// void g(int i) { f(i); }
1164///
1165/// this routine would produce an implicit conversion sequence to
1166/// describe the initialization of f from i, which will be a standard
1167/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1168/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1169//
1170/// Note that this routine only determines how the conversion can be
1171/// performed; it does not actually perform the conversion. As such,
1172/// it will not produce any diagnostics if no conversion is available,
1173/// but will instead return an implicit conversion sequence of kind
1174/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001175///
1176/// If @p SuppressUserConversions, then user-defined conversions are
1177/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001178/// If @p AllowExplicit, then explicit user-defined conversions are
1179/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001180///
1181/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1182/// writeback conversion, which allows __autoreleasing id* parameters to
1183/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001184static ImplicitConversionSequence
1185TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1186 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001187 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001188 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001189 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001190 bool AllowObjCWritebackConversion,
1191 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001192 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001193 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001194 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001195 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001196 return ICS;
1197 }
1198
David Blaikiebbafb8a2012-03-11 07:00:24 +00001199 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001200 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001201 return ICS;
1202 }
1203
Douglas Gregor836a7e82010-08-11 02:15:33 +00001204 // C++ [over.ics.user]p4:
1205 // A conversion of an expression of class type to the same class
1206 // type is given Exact Match rank, and a conversion of an
1207 // expression of class type to a base class of that type is
1208 // given Conversion rank, in spite of the fact that a copy/move
1209 // constructor (i.e., a user-defined conversion function) is
1210 // called for those cases.
1211 QualType FromType = From->getType();
1212 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001213 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1214 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001215 ICS.setStandard();
1216 ICS.Standard.setAsIdentityConversion();
1217 ICS.Standard.setFromType(FromType);
1218 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001219
Douglas Gregor5ab11652010-04-17 22:01:05 +00001220 // We don't actually check at this point whether there is a valid
1221 // copy/move constructor, since overloading just assumes that it
1222 // exists. When we actually perform initialization, we'll find the
1223 // appropriate constructor to copy the returned object, if needed.
Craig Topperc3ec1492014-05-26 06:22:03 +00001224 ICS.Standard.CopyConstructor = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001225
Douglas Gregor5ab11652010-04-17 22:01:05 +00001226 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001227 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001228 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001229
Douglas Gregor836a7e82010-08-11 02:15:33 +00001230 return ICS;
1231 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001232
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001233 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1234 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001235 AllowObjCWritebackConversion,
1236 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001237}
1238
John McCall31168b02011-06-15 23:02:42 +00001239ImplicitConversionSequence
1240Sema::TryImplicitConversion(Expr *From, QualType ToType,
1241 bool SuppressUserConversions,
1242 bool AllowExplicit,
1243 bool InOverloadResolution,
1244 bool CStyle,
1245 bool AllowObjCWritebackConversion) {
Richard Smith17c00b42014-11-12 01:24:00 +00001246 return ::TryImplicitConversion(*this, From, ToType,
1247 SuppressUserConversions, AllowExplicit,
1248 InOverloadResolution, CStyle,
1249 AllowObjCWritebackConversion,
1250 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001251}
1252
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001253/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001254/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001255/// converted expression. Flavor is the kind of conversion we're
1256/// performing, used in the error message. If @p AllowExplicit,
1257/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001258ExprResult
1259Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001260 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001261 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001262 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001263}
1264
John Wiegley01296292011-04-08 18:41:53 +00001265ExprResult
1266Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001267 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001268 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001269 if (checkPlaceholderForOverload(*this, From))
1270 return ExprError();
1271
John McCall31168b02011-06-15 23:02:42 +00001272 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1273 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001274 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001275 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001276 if (getLangOpts().ObjC1)
1277 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1278 ToType, From->getType(), From);
Richard Smith17c00b42014-11-12 01:24:00 +00001279 ICS = ::TryImplicitConversion(*this, From, ToType,
1280 /*SuppressUserConversions=*/false,
1281 AllowExplicit,
1282 /*InOverloadResolution=*/false,
1283 /*CStyle=*/false,
1284 AllowObjCWritebackConversion,
1285 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001286 return PerformImplicitConversion(From, ToType, ICS, Action);
1287}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001288
1289/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001290/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001291bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1292 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001293 if (Context.hasSameUnqualifiedType(FromType, ToType))
1294 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001295
John McCall991eb4b2010-12-21 00:44:39 +00001296 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1297 // where F adds one of the following at most once:
1298 // - a pointer
1299 // - a member pointer
1300 // - a block pointer
1301 CanQualType CanTo = Context.getCanonicalType(ToType);
1302 CanQualType CanFrom = Context.getCanonicalType(FromType);
1303 Type::TypeClass TyClass = CanTo->getTypeClass();
1304 if (TyClass != CanFrom->getTypeClass()) return false;
1305 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1306 if (TyClass == Type::Pointer) {
1307 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1308 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1309 } else if (TyClass == Type::BlockPointer) {
1310 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1311 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1312 } else if (TyClass == Type::MemberPointer) {
1313 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1314 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1315 } else {
1316 return false;
1317 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001318
John McCall991eb4b2010-12-21 00:44:39 +00001319 TyClass = CanTo->getTypeClass();
1320 if (TyClass != CanFrom->getTypeClass()) return false;
1321 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1322 return false;
1323 }
1324
1325 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1326 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1327 if (!EInfo.getNoReturn()) return false;
1328
1329 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1330 assert(QualType(FromFn, 0).isCanonical());
1331 if (QualType(FromFn, 0) != CanTo) return false;
1332
1333 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001334 return true;
1335}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001336
Douglas Gregor46188682010-05-18 22:42:18 +00001337/// \brief Determine whether the conversion from FromType to ToType is a valid
1338/// vector conversion.
1339///
1340/// \param ICK Will be set to the vector conversion kind, if this is a vector
1341/// conversion.
John McCall9b595db2014-02-04 23:58:19 +00001342static bool IsVectorConversion(Sema &S, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001343 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001344 // We need at least one of these types to be a vector type to have a vector
1345 // conversion.
1346 if (!ToType->isVectorType() && !FromType->isVectorType())
1347 return false;
1348
1349 // Identical types require no conversions.
John McCall9b595db2014-02-04 23:58:19 +00001350 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor46188682010-05-18 22:42:18 +00001351 return false;
1352
1353 // There are no conversions between extended vector types, only identity.
1354 if (ToType->isExtVectorType()) {
1355 // There are no conversions between extended vector types other than the
1356 // identity conversion.
1357 if (FromType->isExtVectorType())
1358 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001359
Douglas Gregor46188682010-05-18 22:42:18 +00001360 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001361 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001362 ICK = ICK_Vector_Splat;
1363 return true;
1364 }
1365 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001366
1367 // We can perform the conversion between vector types in the following cases:
1368 // 1)vector types are equivalent AltiVec and GCC vector types
1369 // 2)lax vector conversions are permitted and the vector types are of the
1370 // same size
1371 if (ToType->isVectorType() && FromType->isVectorType()) {
John McCall9b595db2014-02-04 23:58:19 +00001372 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1373 S.isLaxVectorConversion(FromType, ToType)) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001374 ICK = ICK_Vector_Conversion;
1375 return true;
1376 }
Douglas Gregor46188682010-05-18 22:42:18 +00001377 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001378
Douglas Gregor46188682010-05-18 22:42:18 +00001379 return false;
1380}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001381
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001382static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1383 bool InOverloadResolution,
1384 StandardConversionSequence &SCS,
1385 bool CStyle);
Douglas Gregorc79862f2012-04-12 17:51:55 +00001386
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001387/// IsStandardConversion - Determines whether there is a standard
1388/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1389/// expression From to the type ToType. Standard conversion sequences
1390/// only consider non-class types; for conversions that involve class
1391/// types, use TryImplicitConversion. If a conversion exists, SCS will
1392/// contain the standard conversion sequence required to perform this
1393/// conversion and this routine will return true. Otherwise, this
1394/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001395static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1396 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001397 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001398 bool CStyle,
1399 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001400 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001401
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001402 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001403 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001404 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001405 SCS.setFromType(FromType);
Craig Topperc3ec1492014-05-26 06:22:03 +00001406 SCS.CopyConstructor = nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001407
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001408 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001409 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001410 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001411 if (S.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001412 return false;
1413
Mike Stump11289f42009-09-09 15:08:12 +00001414 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001415 }
1416
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001417 // The first conversion can be an lvalue-to-rvalue conversion,
1418 // array-to-pointer conversion, or function-to-pointer conversion
1419 // (C++ 4p1).
1420
John McCall5c32be02010-08-24 20:38:10 +00001421 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001422 DeclAccessPair AccessPair;
1423 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001424 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001425 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001426 // We were able to resolve the address of the overloaded function,
1427 // so we can convert to the type of that function.
1428 FromType = Fn->getType();
Ehsan Akhgaric3ad3ba2014-07-22 20:20:14 +00001429 SCS.setFromType(FromType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001430
1431 // we can sometimes resolve &foo<int> regardless of ToType, so check
1432 // if the type matches (identity) or we are converting to bool
1433 if (!S.Context.hasSameUnqualifiedType(
1434 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1435 QualType resultTy;
1436 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001437 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001438 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1439 // otherwise, only a boolean conversion is standard
1440 if (!ToType->isBooleanType())
1441 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001442 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001443
Chandler Carruthffce2452011-03-29 08:08:18 +00001444 // Check if the "from" expression is taking the address of an overloaded
1445 // function and recompute the FromType accordingly. Take advantage of the
1446 // fact that non-static member functions *must* have such an address-of
1447 // expression.
1448 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1449 if (Method && !Method->isStatic()) {
1450 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1451 "Non-unary operator on non-static member address");
1452 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1453 == UO_AddrOf &&
1454 "Non-address-of operator on non-static member address");
1455 const Type *ClassType
1456 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1457 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001458 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1459 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1460 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001461 "Non-address-of operator for overloaded function expression");
1462 FromType = S.Context.getPointerType(FromType);
1463 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001464
Douglas Gregor980fb162010-04-29 18:24:40 +00001465 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001466 assert(S.Context.hasSameType(
1467 FromType,
1468 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001469 } else {
1470 return false;
1471 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001472 }
John McCall154a2fd2011-08-30 00:57:29 +00001473 // Lvalue-to-rvalue conversion (C++11 4.1):
1474 // A glvalue (3.10) of a non-function, non-array type T can
1475 // be converted to a prvalue.
1476 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001477 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001478 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001479 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001480 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001481
Douglas Gregorc79862f2012-04-12 17:51:55 +00001482 // C11 6.3.2.1p2:
1483 // ... if the lvalue has atomic type, the value has the non-atomic version
1484 // of the type of the lvalue ...
1485 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1486 FromType = Atomic->getValueType();
1487
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001488 // If T is a non-class type, the type of the rvalue is the
1489 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001490 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1491 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001492 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001493 } else if (FromType->isArrayType()) {
1494 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001495 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001496
1497 // An lvalue or rvalue of type "array of N T" or "array of unknown
1498 // bound of T" can be converted to an rvalue of type "pointer to
1499 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001500 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001501
John McCall5c32be02010-08-24 20:38:10 +00001502 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001503 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001504 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001505
1506 // For the purpose of ranking in overload resolution
1507 // (13.3.3.1.1), this conversion is considered an
1508 // array-to-pointer conversion followed by a qualification
1509 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001510 SCS.Second = ICK_Identity;
1511 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001512 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001513 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001514 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001515 }
John McCall086a4642010-11-24 05:12:34 +00001516 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001517 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001518 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001519
1520 // An lvalue of function type T can be converted to an rvalue of
1521 // type "pointer to T." The result is a pointer to the
1522 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001523 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001524 } else {
1525 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001526 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001527 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001528 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001529
1530 // The second conversion can be an integral promotion, floating
1531 // point promotion, integral conversion, floating point conversion,
1532 // floating-integral conversion, pointer conversion,
1533 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001534 // For overloading in C, this can also be a "compatible-type"
1535 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001536 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001537 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001538 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001539 // The unqualified versions of the types are the same: there's no
1540 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001541 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001542 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001543 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001544 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001545 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001546 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001547 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001548 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001549 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001550 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001551 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001552 SCS.Second = ICK_Complex_Promotion;
1553 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001554 } else if (ToType->isBooleanType() &&
1555 (FromType->isArithmeticType() ||
1556 FromType->isAnyPointerType() ||
1557 FromType->isBlockPointerType() ||
1558 FromType->isMemberPointerType() ||
1559 FromType->isNullPtrType())) {
1560 // Boolean conversions (C++ 4.12).
1561 SCS.Second = ICK_Boolean_Conversion;
1562 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001563 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001564 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001565 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001566 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001567 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001568 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001569 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001570 SCS.Second = ICK_Complex_Conversion;
1571 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001572 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1573 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001574 // Complex-real conversions (C99 6.3.1.7)
1575 SCS.Second = ICK_Complex_Real;
1576 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001577 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001578 // Floating point conversions (C++ 4.8).
1579 SCS.Second = ICK_Floating_Conversion;
1580 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001581 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001582 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001583 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001584 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001585 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001586 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001587 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001588 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001589 SCS.Second = ICK_Block_Pointer_Conversion;
1590 } else if (AllowObjCWritebackConversion &&
1591 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1592 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001593 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1594 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001595 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001596 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001597 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001598 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001599 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001600 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001601 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001602 SCS.Second = ICK_Pointer_Member;
John McCall9b595db2014-02-04 23:58:19 +00001603 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001604 SCS.Second = SecondICK;
1605 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001606 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001607 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001608 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001609 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001610 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001611 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001612 // Treat a conversion that strips "noreturn" as an identity conversion.
1613 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001614 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1615 InOverloadResolution,
1616 SCS, CStyle)) {
1617 SCS.Second = ICK_TransparentUnionConversion;
1618 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001619 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1620 CStyle)) {
1621 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001622 // appropriately.
1623 return true;
Guy Benyei259f9f42013-02-07 16:05:33 +00001624 } else if (ToType->isEventT() &&
1625 From->isIntegerConstantExpr(S.getASTContext()) &&
1626 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1627 SCS.Second = ICK_Zero_Event_Conversion;
1628 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001629 } else {
1630 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001631 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001632 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001633 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001634
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001635 QualType CanonFrom;
1636 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001637 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001638 bool ObjCLifetimeConversion;
1639 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1640 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001641 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001642 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001643 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001644 CanonFrom = S.Context.getCanonicalType(FromType);
1645 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001646 } else {
1647 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001648 SCS.Third = ICK_Identity;
1649
Mike Stump11289f42009-09-09 15:08:12 +00001650 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001651 // [...] Any difference in top-level cv-qualification is
1652 // subsumed by the initialization itself and does not constitute
1653 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001654 CanonFrom = S.Context.getCanonicalType(FromType);
1655 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001656 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001657 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault7d36c012013-02-26 21:15:54 +00001658 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001659 FromType = ToType;
1660 CanonFrom = CanonTo;
1661 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001662 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001663 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001664
1665 // If we have not converted the argument type to the parameter type,
1666 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001667 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001668 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001669
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001670 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001671}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001672
1673static bool
1674IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1675 QualType &ToType,
1676 bool InOverloadResolution,
1677 StandardConversionSequence &SCS,
1678 bool CStyle) {
1679
1680 const RecordType *UT = ToType->getAsUnionType();
1681 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1682 return false;
1683 // The field to initialize within the transparent union.
1684 RecordDecl *UD = UT->getDecl();
1685 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001686 for (const auto *it : UD->fields()) {
John McCall31168b02011-06-15 23:02:42 +00001687 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1688 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001689 ToType = it->getType();
1690 return true;
1691 }
1692 }
1693 return false;
1694}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001695
1696/// IsIntegralPromotion - Determines whether the conversion from the
1697/// expression From (whose potentially-adjusted type is FromType) to
1698/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1699/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001700bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001701 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001702 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001703 if (!To) {
1704 return false;
1705 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001706
1707 // An rvalue of type char, signed char, unsigned char, short int, or
1708 // unsigned short int can be converted to an rvalue of type int if
1709 // int can represent all the values of the source type; otherwise,
1710 // the source rvalue can be converted to an rvalue of type unsigned
1711 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001712 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1713 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001714 if (// We can promote any signed, promotable integer type to an int
1715 (FromType->isSignedIntegerType() ||
1716 // We can promote any unsigned integer type whose size is
1717 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001718 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001719 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001720 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001721 }
1722
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001723 return To->getKind() == BuiltinType::UInt;
1724 }
1725
Richard Smithb9c5a602012-09-13 21:18:54 +00001726 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001727 // A prvalue of an unscoped enumeration type whose underlying type is not
1728 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1729 // following types that can represent all the values of the enumeration
1730 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1731 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001732 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001733 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001734 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001735 // with lowest integer conversion rank (4.13) greater than the rank of long
1736 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001737 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001738 // C++11 [conv.prom]p4:
1739 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1740 // can be converted to a prvalue of its underlying type. Moreover, if
1741 // integral promotion can be applied to its underlying type, a prvalue of an
1742 // unscoped enumeration type whose underlying type is fixed can also be
1743 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001744 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1745 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1746 // provided for a scoped enumeration.
1747 if (FromEnumType->getDecl()->isScoped())
1748 return false;
1749
Richard Smithb9c5a602012-09-13 21:18:54 +00001750 // We can perform an integral promotion to the underlying type of the enum,
1751 // even if that's not the promoted type.
1752 if (FromEnumType->getDecl()->isFixed()) {
1753 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1754 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1755 IsIntegralPromotion(From, Underlying, ToType);
1756 }
1757
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001758 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001759 if (ToType->isIntegerType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001760 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall56774992009-12-09 09:09:27 +00001761 return Context.hasSameUnqualifiedType(ToType,
1762 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001763 }
John McCall56774992009-12-09 09:09:27 +00001764
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001765 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001766 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1767 // to an rvalue a prvalue of the first of the following types that can
1768 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001769 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001770 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001771 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001772 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001773 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001774 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001775 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001776 // Determine whether the type we're converting from is signed or
1777 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001778 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001779 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001780
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001781 // The types we'll try to promote to, in the appropriate
1782 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001783 QualType PromoteTypes[6] = {
1784 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001785 Context.LongTy, Context.UnsignedLongTy ,
1786 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001787 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001788 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001789 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1790 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001791 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001792 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1793 // We found the type that we can promote to. If this is the
1794 // type we wanted, we have a promotion. Otherwise, no
1795 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001796 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001797 }
1798 }
1799 }
1800
1801 // An rvalue for an integral bit-field (9.6) can be converted to an
1802 // rvalue of type int if int can represent all the values of the
1803 // bit-field; otherwise, it can be converted to unsigned int if
1804 // unsigned int can represent all the values of the bit-field. If
1805 // the bit-field is larger yet, no integral promotion applies to
1806 // it. If the bit-field has an enumerated type, it is treated as any
1807 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001808 // FIXME: We should delay checking of bit-fields until we actually perform the
1809 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001810 using llvm::APSInt;
1811 if (From)
John McCalld25db7e2013-05-06 21:39:12 +00001812 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001813 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001814 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001815 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1816 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1817 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001818
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001819 // Are we promoting to an int from a bitfield that fits in an int?
1820 if (BitWidth < ToSize ||
1821 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1822 return To->getKind() == BuiltinType::Int;
1823 }
Mike Stump11289f42009-09-09 15:08:12 +00001824
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001825 // Are we promoting to an unsigned int from an unsigned bitfield
1826 // that fits into an unsigned int?
1827 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1828 return To->getKind() == BuiltinType::UInt;
1829 }
Mike Stump11289f42009-09-09 15:08:12 +00001830
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001831 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001832 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001833 }
Mike Stump11289f42009-09-09 15:08:12 +00001834
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001835 // An rvalue of type bool can be converted to an rvalue of type int,
1836 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001837 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001838 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001839 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001840
1841 return false;
1842}
1843
1844/// IsFloatingPointPromotion - Determines whether the conversion from
1845/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1846/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001847bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001848 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1849 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001850 /// An rvalue of type float can be converted to an rvalue of type
1851 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001852 if (FromBuiltin->getKind() == BuiltinType::Float &&
1853 ToBuiltin->getKind() == BuiltinType::Double)
1854 return true;
1855
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001856 // C99 6.3.1.5p1:
1857 // When a float is promoted to double or long double, or a
1858 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00001859 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001860 (FromBuiltin->getKind() == BuiltinType::Float ||
1861 FromBuiltin->getKind() == BuiltinType::Double) &&
1862 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1863 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001864
1865 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00001866 if (!getLangOpts().NativeHalfType &&
1867 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001868 ToBuiltin->getKind() == BuiltinType::Float)
1869 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001870 }
1871
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001872 return false;
1873}
1874
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001875/// \brief Determine if a conversion is a complex promotion.
1876///
1877/// A complex promotion is defined as a complex -> complex conversion
1878/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001879/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001880bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001881 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001882 if (!FromComplex)
1883 return false;
1884
John McCall9dd450b2009-09-21 23:43:11 +00001885 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001886 if (!ToComplex)
1887 return false;
1888
1889 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001890 ToComplex->getElementType()) ||
Craig Topperc3ec1492014-05-26 06:22:03 +00001891 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001892 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001893}
1894
Douglas Gregor237f96c2008-11-26 23:31:11 +00001895/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1896/// the pointer type FromPtr to a pointer to type ToPointee, with the
1897/// same type qualifiers as FromPtr has on its pointee type. ToType,
1898/// if non-empty, will be a pointer to ToType that may or may not have
1899/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001900///
Mike Stump11289f42009-09-09 15:08:12 +00001901static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001902BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001903 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001904 ASTContext &Context,
1905 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001906 assert((FromPtr->getTypeClass() == Type::Pointer ||
1907 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1908 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001909
John McCall31168b02011-06-15 23:02:42 +00001910 /// Conversions to 'id' subsume cv-qualifier conversions.
1911 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001912 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001913
1914 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001915 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001916 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001917 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001918
John McCall31168b02011-06-15 23:02:42 +00001919 if (StripObjCLifetime)
1920 Quals.removeObjCLifetime();
1921
Mike Stump11289f42009-09-09 15:08:12 +00001922 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001923 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001924 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001925 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001926 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001927
1928 // Build a pointer to ToPointee. It has the right qualifiers
1929 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001930 if (isa<ObjCObjectPointerType>(ToType))
1931 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001932 return Context.getPointerType(ToPointee);
1933 }
1934
1935 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001936 QualType QualifiedCanonToPointee
1937 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001938
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001939 if (isa<ObjCObjectPointerType>(ToType))
1940 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1941 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001942}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001943
Mike Stump11289f42009-09-09 15:08:12 +00001944static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001945 bool InOverloadResolution,
1946 ASTContext &Context) {
1947 // Handle value-dependent integral null pointer constants correctly.
1948 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1949 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001950 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001951 return !InOverloadResolution;
1952
Douglas Gregor56751b52009-09-25 04:25:58 +00001953 return Expr->isNullPointerConstant(Context,
1954 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1955 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001956}
Mike Stump11289f42009-09-09 15:08:12 +00001957
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001958/// IsPointerConversion - Determines whether the conversion of the
1959/// expression From, which has the (possibly adjusted) type FromType,
1960/// can be converted to the type ToType via a pointer conversion (C++
1961/// 4.10). If so, returns true and places the converted type (that
1962/// might differ from ToType in its cv-qualifiers at some level) into
1963/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001964///
Douglas Gregora29dc052008-11-27 01:19:21 +00001965/// This routine also supports conversions to and from block pointers
1966/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1967/// pointers to interfaces. FIXME: Once we've determined the
1968/// appropriate overloading rules for Objective-C, we may want to
1969/// split the Objective-C checks into a different routine; however,
1970/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001971/// conversions, so for now they live here. IncompatibleObjC will be
1972/// set if the conversion is an allowed Objective-C conversion that
1973/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001974bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001975 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001976 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001977 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001978 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001979 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1980 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001981 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001982
Mike Stump11289f42009-09-09 15:08:12 +00001983 // Conversion from a null pointer constant to any Objective-C pointer type.
1984 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001985 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001986 ConvertedType = ToType;
1987 return true;
1988 }
1989
Douglas Gregor231d1c62008-11-27 00:15:41 +00001990 // Blocks: Block pointers can be converted to void*.
1991 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001992 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001993 ConvertedType = ToType;
1994 return true;
1995 }
1996 // Blocks: A null pointer constant can be converted to a block
1997 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001998 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001999 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002000 ConvertedType = ToType;
2001 return true;
2002 }
2003
Sebastian Redl576fd422009-05-10 18:38:11 +00002004 // If the left-hand-side is nullptr_t, the right side can be a null
2005 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002006 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002007 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002008 ConvertedType = ToType;
2009 return true;
2010 }
2011
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002012 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002013 if (!ToTypePtr)
2014 return false;
2015
2016 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002017 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002018 ConvertedType = ToType;
2019 return true;
2020 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002021
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002022 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002023 // , including objective-c pointers.
2024 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002025 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002026 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002027 ConvertedType = BuildSimilarlyQualifiedPointerType(
2028 FromType->getAs<ObjCObjectPointerType>(),
2029 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002030 ToType, Context);
2031 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002032 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002033 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002034 if (!FromTypePtr)
2035 return false;
2036
2037 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002038
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002039 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002040 // pointer conversion, so don't do all of the work below.
2041 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2042 return false;
2043
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002044 // An rvalue of type "pointer to cv T," where T is an object type,
2045 // can be converted to an rvalue of type "pointer to cv void" (C++
2046 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002047 if (FromPointeeType->isIncompleteOrObjectType() &&
2048 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002049 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002050 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002051 ToType, Context,
2052 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002053 return true;
2054 }
2055
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002056 // MSVC allows implicit function to void* type conversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002057 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002058 ToPointeeType->isVoidType()) {
2059 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2060 ToPointeeType,
2061 ToType, Context);
2062 return true;
2063 }
2064
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002065 // When we're overloading in C, we allow a special kind of pointer
2066 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002067 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002068 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002069 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002070 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002071 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002072 return true;
2073 }
2074
Douglas Gregor5c407d92008-10-23 00:40:37 +00002075 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002076 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002077 // An rvalue of type "pointer to cv D," where D is a class type,
2078 // can be converted to an rvalue of type "pointer to cv B," where
2079 // B is a base class (clause 10) of D. If B is an inaccessible
2080 // (clause 11) or ambiguous (10.2) base class of D, a program that
2081 // necessitates this conversion is ill-formed. The result of the
2082 // conversion is a pointer to the base class sub-object of the
2083 // derived class object. The null pointer value is converted to
2084 // the null pointer value of the destination type.
2085 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002086 // Note that we do not check for ambiguity or inaccessibility
2087 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002088 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002089 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002090 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002091 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00002092 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002093 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002094 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002095 ToType, Context);
2096 return true;
2097 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002098
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002099 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2100 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2101 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2102 ToPointeeType,
2103 ToType, Context);
2104 return true;
2105 }
2106
Douglas Gregora119f102008-12-19 19:13:09 +00002107 return false;
2108}
Douglas Gregoraec25842011-04-26 23:16:46 +00002109
2110/// \brief Adopt the given qualifiers for the given type.
2111static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2112 Qualifiers TQs = T.getQualifiers();
2113
2114 // Check whether qualifiers already match.
2115 if (TQs == Qs)
2116 return T;
2117
2118 if (Qs.compatiblyIncludes(TQs))
2119 return Context.getQualifiedType(T, Qs);
2120
2121 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2122}
Douglas Gregora119f102008-12-19 19:13:09 +00002123
2124/// isObjCPointerConversion - Determines whether this is an
2125/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2126/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002127bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002128 QualType& ConvertedType,
2129 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002130 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002131 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002132
Douglas Gregoraec25842011-04-26 23:16:46 +00002133 // The set of qualifiers on the type we're converting from.
2134 Qualifiers FromQualifiers = FromType.getQualifiers();
2135
Steve Naroff7cae42b2009-07-10 23:34:53 +00002136 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002137 const ObjCObjectPointerType* ToObjCPtr =
2138 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002139 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002140 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002141
Steve Naroff7cae42b2009-07-10 23:34:53 +00002142 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002143 // If the pointee types are the same (ignoring qualifications),
2144 // then this is not a pointer conversion.
2145 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2146 FromObjCPtr->getPointeeType()))
2147 return false;
2148
Douglas Gregoraec25842011-04-26 23:16:46 +00002149 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00002150 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00002151 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00002152 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002153 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002154 return true;
2155 }
2156 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00002157 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00002158 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00002159 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00002160 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002161 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002162 return true;
2163 }
2164 // Objective C++: We're able to convert from a pointer to an
2165 // interface to a pointer to a different interface.
2166 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002167 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2168 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002169 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002170 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2171 FromObjCPtr->getPointeeType()))
2172 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002173 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002174 ToObjCPtr->getPointeeType(),
2175 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002176 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002177 return true;
2178 }
2179
2180 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2181 // Okay: this is some kind of implicit downcast of Objective-C
2182 // interfaces, which is permitted. However, we're going to
2183 // complain about it.
2184 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002185 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002186 ToObjCPtr->getPointeeType(),
2187 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002188 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002189 return true;
2190 }
Mike Stump11289f42009-09-09 15:08:12 +00002191 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002192 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002193 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002194 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002195 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002196 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002197 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002198 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002199 // to a block pointer type.
2200 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002201 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002202 return true;
2203 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002204 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002205 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002206 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002207 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002208 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002209 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002210 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002211 return true;
2212 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002213 else
Douglas Gregora119f102008-12-19 19:13:09 +00002214 return false;
2215
Douglas Gregor033f56d2008-12-23 00:53:59 +00002216 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002217 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002218 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002219 else if (const BlockPointerType *FromBlockPtr =
2220 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002221 FromPointeeType = FromBlockPtr->getPointeeType();
2222 else
Douglas Gregora119f102008-12-19 19:13:09 +00002223 return false;
2224
Douglas Gregora119f102008-12-19 19:13:09 +00002225 // If we have pointers to pointers, recursively check whether this
2226 // is an Objective-C conversion.
2227 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2228 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2229 IncompatibleObjC)) {
2230 // We always complain about this conversion.
2231 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002232 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002233 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002234 return true;
2235 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002236 // Allow conversion of pointee being objective-c pointer to another one;
2237 // as in I* to id.
2238 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2239 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2240 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2241 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002242
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002243 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002244 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002245 return true;
2246 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002247
Douglas Gregor033f56d2008-12-23 00:53:59 +00002248 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002249 // differences in the argument and result types are in Objective-C
2250 // pointer conversions. If so, we permit the conversion (but
2251 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002252 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002253 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002254 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002255 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002256 if (FromFunctionType && ToFunctionType) {
2257 // If the function types are exactly the same, this isn't an
2258 // Objective-C pointer conversion.
2259 if (Context.getCanonicalType(FromPointeeType)
2260 == Context.getCanonicalType(ToPointeeType))
2261 return false;
2262
2263 // Perform the quick checks that will tell us whether these
2264 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002265 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002266 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2267 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2268 return false;
2269
2270 bool HasObjCConversion = false;
Alp Toker314cc812014-01-25 16:55:45 +00002271 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2272 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregora119f102008-12-19 19:13:09 +00002273 // Okay, the types match exactly. Nothing to do.
Alp Toker314cc812014-01-25 16:55:45 +00002274 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2275 ToFunctionType->getReturnType(),
Douglas Gregora119f102008-12-19 19:13:09 +00002276 ConvertedType, IncompatibleObjC)) {
2277 // Okay, we have an Objective-C pointer conversion.
2278 HasObjCConversion = true;
2279 } else {
2280 // Function types are too different. Abort.
2281 return false;
2282 }
Mike Stump11289f42009-09-09 15:08:12 +00002283
Douglas Gregora119f102008-12-19 19:13:09 +00002284 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002285 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002286 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002287 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2288 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002289 if (Context.getCanonicalType(FromArgType)
2290 == Context.getCanonicalType(ToArgType)) {
2291 // Okay, the types match exactly. Nothing to do.
2292 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2293 ConvertedType, IncompatibleObjC)) {
2294 // Okay, we have an Objective-C pointer conversion.
2295 HasObjCConversion = true;
2296 } else {
2297 // Argument types are too different. Abort.
2298 return false;
2299 }
2300 }
2301
2302 if (HasObjCConversion) {
2303 // We had an Objective-C conversion. Allow this pointer
2304 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002305 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002306 IncompatibleObjC = true;
2307 return true;
2308 }
2309 }
2310
Sebastian Redl72b597d2009-01-25 19:43:20 +00002311 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002312}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002313
John McCall31168b02011-06-15 23:02:42 +00002314/// \brief Determine whether this is an Objective-C writeback conversion,
2315/// used for parameter passing when performing automatic reference counting.
2316///
2317/// \param FromType The type we're converting form.
2318///
2319/// \param ToType The type we're converting to.
2320///
2321/// \param ConvertedType The type that will be produced after applying
2322/// this conversion.
2323bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2324 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002325 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002326 Context.hasSameUnqualifiedType(FromType, ToType))
2327 return false;
2328
2329 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2330 QualType ToPointee;
2331 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2332 ToPointee = ToPointer->getPointeeType();
2333 else
2334 return false;
2335
2336 Qualifiers ToQuals = ToPointee.getQualifiers();
2337 if (!ToPointee->isObjCLifetimeType() ||
2338 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002339 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002340 return false;
2341
2342 // Argument must be a pointer to __strong to __weak.
2343 QualType FromPointee;
2344 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2345 FromPointee = FromPointer->getPointeeType();
2346 else
2347 return false;
2348
2349 Qualifiers FromQuals = FromPointee.getQualifiers();
2350 if (!FromPointee->isObjCLifetimeType() ||
2351 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2352 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2353 return false;
2354
2355 // Make sure that we have compatible qualifiers.
2356 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2357 if (!ToQuals.compatiblyIncludes(FromQuals))
2358 return false;
2359
2360 // Remove qualifiers from the pointee type we're converting from; they
2361 // aren't used in the compatibility check belong, and we'll be adding back
2362 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2363 FromPointee = FromPointee.getUnqualifiedType();
2364
2365 // The unqualified form of the pointee types must be compatible.
2366 ToPointee = ToPointee.getUnqualifiedType();
2367 bool IncompatibleObjC;
2368 if (Context.typesAreCompatible(FromPointee, ToPointee))
2369 FromPointee = ToPointee;
2370 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2371 IncompatibleObjC))
2372 return false;
2373
2374 /// \brief Construct the type we're converting to, which is a pointer to
2375 /// __autoreleasing pointee.
2376 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2377 ConvertedType = Context.getPointerType(FromPointee);
2378 return true;
2379}
2380
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002381bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2382 QualType& ConvertedType) {
2383 QualType ToPointeeType;
2384 if (const BlockPointerType *ToBlockPtr =
2385 ToType->getAs<BlockPointerType>())
2386 ToPointeeType = ToBlockPtr->getPointeeType();
2387 else
2388 return false;
2389
2390 QualType FromPointeeType;
2391 if (const BlockPointerType *FromBlockPtr =
2392 FromType->getAs<BlockPointerType>())
2393 FromPointeeType = FromBlockPtr->getPointeeType();
2394 else
2395 return false;
2396 // We have pointer to blocks, check whether the only
2397 // differences in the argument and result types are in Objective-C
2398 // pointer conversions. If so, we permit the conversion.
2399
2400 const FunctionProtoType *FromFunctionType
2401 = FromPointeeType->getAs<FunctionProtoType>();
2402 const FunctionProtoType *ToFunctionType
2403 = ToPointeeType->getAs<FunctionProtoType>();
2404
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002405 if (!FromFunctionType || !ToFunctionType)
2406 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002407
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002408 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002409 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002410
2411 // Perform the quick checks that will tell us whether these
2412 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002413 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002414 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2415 return false;
2416
2417 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2418 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2419 if (FromEInfo != ToEInfo)
2420 return false;
2421
2422 bool IncompatibleObjC = false;
Alp Toker314cc812014-01-25 16:55:45 +00002423 if (Context.hasSameType(FromFunctionType->getReturnType(),
2424 ToFunctionType->getReturnType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002425 // Okay, the types match exactly. Nothing to do.
2426 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002427 QualType RHS = FromFunctionType->getReturnType();
2428 QualType LHS = ToFunctionType->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002429 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002430 !RHS.hasQualifiers() && LHS.hasQualifiers())
2431 LHS = LHS.getUnqualifiedType();
2432
2433 if (Context.hasSameType(RHS,LHS)) {
2434 // OK exact match.
2435 } else if (isObjCPointerConversion(RHS, LHS,
2436 ConvertedType, IncompatibleObjC)) {
2437 if (IncompatibleObjC)
2438 return false;
2439 // Okay, we have an Objective-C pointer conversion.
2440 }
2441 else
2442 return false;
2443 }
2444
2445 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002446 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002447 ArgIdx != NumArgs; ++ArgIdx) {
2448 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002449 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2450 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002451 if (Context.hasSameType(FromArgType, ToArgType)) {
2452 // Okay, the types match exactly. Nothing to do.
2453 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2454 ConvertedType, IncompatibleObjC)) {
2455 if (IncompatibleObjC)
2456 return false;
2457 // Okay, we have an Objective-C pointer conversion.
2458 } else
2459 // Argument types are too different. Abort.
2460 return false;
2461 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002462 if (LangOpts.ObjCAutoRefCount &&
2463 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2464 ToFunctionType))
2465 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002466
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002467 ConvertedType = ToType;
2468 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002469}
2470
Richard Trieucaff2472011-11-23 22:32:32 +00002471enum {
2472 ft_default,
2473 ft_different_class,
2474 ft_parameter_arity,
2475 ft_parameter_mismatch,
2476 ft_return_type,
2477 ft_qualifer_mismatch
2478};
2479
2480/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2481/// function types. Catches different number of parameter, mismatch in
2482/// parameter types, and different return types.
2483void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2484 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002485 // If either type is not valid, include no extra info.
2486 if (FromType.isNull() || ToType.isNull()) {
2487 PDiag << ft_default;
2488 return;
2489 }
2490
Richard Trieucaff2472011-11-23 22:32:32 +00002491 // Get the function type from the pointers.
2492 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2493 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2494 *ToMember = ToType->getAs<MemberPointerType>();
Richard Trieu9098c9f2014-05-22 01:39:16 +00002495 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
Richard Trieucaff2472011-11-23 22:32:32 +00002496 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2497 << QualType(FromMember->getClass(), 0);
2498 return;
2499 }
2500 FromType = FromMember->getPointeeType();
2501 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002502 }
2503
Richard Trieu96ed5b62011-12-13 23:19:45 +00002504 if (FromType->isPointerType())
2505 FromType = FromType->getPointeeType();
2506 if (ToType->isPointerType())
2507 ToType = ToType->getPointeeType();
2508
2509 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002510 FromType = FromType.getNonReferenceType();
2511 ToType = ToType.getNonReferenceType();
2512
Richard Trieucaff2472011-11-23 22:32:32 +00002513 // Don't print extra info for non-specialized template functions.
2514 if (FromType->isInstantiationDependentType() &&
2515 !FromType->getAs<TemplateSpecializationType>()) {
2516 PDiag << ft_default;
2517 return;
2518 }
2519
Richard Trieu96ed5b62011-12-13 23:19:45 +00002520 // No extra info for same types.
2521 if (Context.hasSameType(FromType, ToType)) {
2522 PDiag << ft_default;
2523 return;
2524 }
2525
Richard Trieucaff2472011-11-23 22:32:32 +00002526 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2527 *ToFunction = ToType->getAs<FunctionProtoType>();
2528
2529 // Both types need to be function types.
2530 if (!FromFunction || !ToFunction) {
2531 PDiag << ft_default;
2532 return;
2533 }
2534
Alp Toker9cacbab2014-01-20 20:26:09 +00002535 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2536 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2537 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002538 return;
2539 }
2540
2541 // Handle different parameter types.
2542 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002543 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002544 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002545 << ToFunction->getParamType(ArgPos)
2546 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002547 return;
2548 }
2549
2550 // Handle different return type.
Alp Toker314cc812014-01-25 16:55:45 +00002551 if (!Context.hasSameType(FromFunction->getReturnType(),
2552 ToFunction->getReturnType())) {
2553 PDiag << ft_return_type << ToFunction->getReturnType()
2554 << FromFunction->getReturnType();
Richard Trieucaff2472011-11-23 22:32:32 +00002555 return;
2556 }
2557
2558 unsigned FromQuals = FromFunction->getTypeQuals(),
2559 ToQuals = ToFunction->getTypeQuals();
2560 if (FromQuals != ToQuals) {
2561 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2562 return;
2563 }
2564
2565 // Unable to find a difference, so add no extra info.
2566 PDiag << ft_default;
2567}
2568
Alp Toker9cacbab2014-01-20 20:26:09 +00002569/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002570/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002571/// they have same number of arguments. If the parameters are different,
2572/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002573bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2574 const FunctionProtoType *NewType,
2575 unsigned *ArgPos) {
2576 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2577 N = NewType->param_type_begin(),
2578 E = OldType->param_type_end();
2579 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002580 if (!Context.hasSameType(O->getUnqualifiedType(),
2581 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002582 if (ArgPos)
2583 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002584 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002585 }
2586 }
2587 return true;
2588}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002589
Douglas Gregor39c16d42008-10-24 04:54:22 +00002590/// CheckPointerConversion - Check the pointer conversion from the
2591/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002592/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002593/// conversions for which IsPointerConversion has already returned
2594/// true. It returns true and produces a diagnostic if there was an
2595/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002596bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002597 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002598 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002599 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002600 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002601 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002602
John McCall8cb679e2010-11-15 09:13:47 +00002603 Kind = CK_BitCast;
2604
David Blaikie1c7c8f72012-08-08 17:33:31 +00002605 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
Argyrios Kyrtzidis3e3305d2014-02-02 05:26:43 +00002606 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
David Blaikie1c7c8f72012-08-08 17:33:31 +00002607 Expr::NPCK_ZeroExpression) {
2608 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2609 DiagRuntimeBehavior(From->getExprLoc(), From,
2610 PDiag(diag::warn_impcast_bool_to_null_pointer)
2611 << ToType << From->getSourceRange());
2612 else if (!isUnevaluatedContext())
2613 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2614 << ToType << From->getSourceRange();
2615 }
John McCall9320b872011-09-09 05:25:32 +00002616 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2617 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002618 QualType FromPointeeType = FromPtrType->getPointeeType(),
2619 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002620
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002621 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2622 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002623 // We must have a derived-to-base conversion. Check an
2624 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002625 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2626 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002627 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002628 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002629 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002630
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002631 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002632 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002633 }
2634 }
John McCall9320b872011-09-09 05:25:32 +00002635 } else if (const ObjCObjectPointerType *ToPtrType =
2636 ToType->getAs<ObjCObjectPointerType>()) {
2637 if (const ObjCObjectPointerType *FromPtrType =
2638 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002639 // Objective-C++ conversions are always okay.
2640 // FIXME: We should have a different class of conversions for the
2641 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002642 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002643 return false;
John McCall9320b872011-09-09 05:25:32 +00002644 } else if (FromType->isBlockPointerType()) {
2645 Kind = CK_BlockPointerToObjCPointerCast;
2646 } else {
2647 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002648 }
John McCall9320b872011-09-09 05:25:32 +00002649 } else if (ToType->isBlockPointerType()) {
2650 if (!FromType->isBlockPointerType())
2651 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002652 }
John McCall8cb679e2010-11-15 09:13:47 +00002653
2654 // We shouldn't fall into this case unless it's valid for other
2655 // reasons.
2656 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2657 Kind = CK_NullToPointer;
2658
Douglas Gregor39c16d42008-10-24 04:54:22 +00002659 return false;
2660}
2661
Sebastian Redl72b597d2009-01-25 19:43:20 +00002662/// IsMemberPointerConversion - Determines whether the conversion of the
2663/// expression From, which has the (possibly adjusted) type FromType, can be
2664/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2665/// If so, returns true and places the converted type (that might differ from
2666/// ToType in its cv-qualifiers at some level) into ConvertedType.
2667bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002668 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002669 bool InOverloadResolution,
2670 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002671 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002672 if (!ToTypePtr)
2673 return false;
2674
2675 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002676 if (From->isNullPointerConstant(Context,
2677 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2678 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002679 ConvertedType = ToType;
2680 return true;
2681 }
2682
2683 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002684 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002685 if (!FromTypePtr)
2686 return false;
2687
2688 // A pointer to member of B can be converted to a pointer to member of D,
2689 // where D is derived from B (C++ 4.11p2).
2690 QualType FromClass(FromTypePtr->getClass(), 0);
2691 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002692
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002693 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002694 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002695 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002696 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2697 ToClass.getTypePtr());
2698 return true;
2699 }
2700
2701 return false;
2702}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002703
Sebastian Redl72b597d2009-01-25 19:43:20 +00002704/// CheckMemberPointerConversion - Check the member pointer conversion from the
2705/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002706/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002707/// for which IsMemberPointerConversion has already returned true. It returns
2708/// true and produces a diagnostic if there was an error, or returns false
2709/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002710bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002711 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002712 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002713 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002714 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002715 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002716 if (!FromPtrType) {
2717 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002718 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002719 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002720 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002721 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002722 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002723 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002724
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002725 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002726 assert(ToPtrType && "No member pointer cast has a target type "
2727 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002728
Sebastian Redled8f2002009-01-28 18:33:18 +00002729 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2730 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002731
Sebastian Redled8f2002009-01-28 18:33:18 +00002732 // FIXME: What about dependent types?
2733 assert(FromClass->isRecordType() && "Pointer into non-class.");
2734 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002735
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002736 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002737 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002738 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2739 assert(DerivationOkay &&
2740 "Should not have been called if derivation isn't OK.");
2741 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002742
Sebastian Redled8f2002009-01-28 18:33:18 +00002743 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2744 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002745 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2746 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2747 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2748 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002749 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002750
Douglas Gregor89ee6822009-02-28 01:32:25 +00002751 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002752 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2753 << FromClass << ToClass << QualType(VBase, 0)
2754 << From->getSourceRange();
2755 return true;
2756 }
2757
John McCall5b0829a2010-02-10 09:31:12 +00002758 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002759 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2760 Paths.front(),
2761 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002762
Anders Carlssond7923c62009-08-22 23:33:40 +00002763 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002764 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002765 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002766 return false;
2767}
2768
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002769/// Determine whether the lifetime conversion between the two given
2770/// qualifiers sets is nontrivial.
2771static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2772 Qualifiers ToQuals) {
2773 // Converting anything to const __unsafe_unretained is trivial.
2774 if (ToQuals.hasConst() &&
2775 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2776 return false;
2777
2778 return true;
2779}
2780
Douglas Gregor9a657932008-10-21 23:43:52 +00002781/// IsQualificationConversion - Determines whether the conversion from
2782/// an rvalue of type FromType to ToType is a qualification conversion
2783/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002784///
2785/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2786/// when the qualification conversion involves a change in the Objective-C
2787/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002788bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002789Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002790 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002791 FromType = Context.getCanonicalType(FromType);
2792 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002793 ObjCLifetimeConversion = false;
2794
Douglas Gregor9a657932008-10-21 23:43:52 +00002795 // If FromType and ToType are the same type, this is not a
2796 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002797 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002798 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002799
Douglas Gregor9a657932008-10-21 23:43:52 +00002800 // (C++ 4.4p4):
2801 // A conversion can add cv-qualifiers at levels other than the first
2802 // in multi-level pointers, subject to the following rules: [...]
2803 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002804 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002805 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002806 // Within each iteration of the loop, we check the qualifiers to
2807 // determine if this still looks like a qualification
2808 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002809 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002810 // until there are no more pointers or pointers-to-members left to
2811 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002812 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002813
Douglas Gregor90609aa2011-04-25 18:40:17 +00002814 Qualifiers FromQuals = FromType.getQualifiers();
2815 Qualifiers ToQuals = ToType.getQualifiers();
2816
John McCall31168b02011-06-15 23:02:42 +00002817 // Objective-C ARC:
2818 // Check Objective-C lifetime conversions.
2819 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2820 UnwrappedAnyPointer) {
2821 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002822 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2823 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00002824 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 Gregorf30053d2011-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 Gregor9a657932008-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 Gregor90609aa2011-04-25 18:40:17 +00002842 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002843 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002844
Douglas Gregor9a657932008-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 Gregor90609aa2011-04-25 18:40:17 +00002847 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002848 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002849 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002850
Douglas Gregor9a657932008-10-21 23:43:52 +00002851 // Keep track of whether all prior cv-qualifiers in the "to" type
2852 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002853 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002854 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002855 }
Douglas Gregor9a657932008-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 Gregor1b8fe5b72009-11-16 21:35:15 +00002862 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002863}
2864
Douglas Gregorc79862f2012-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 Gregorf9e36cc2012-04-12 20:48:09 +00002870static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2871 bool InOverloadResolution,
2872 StandardConversionSequence &SCS,
2873 bool CStyle) {
Douglas Gregorc79862f2012-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 Redle5417162012-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>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002898 if (CtorType->getNumParams() > 0) {
2899 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00002900 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2901 return true;
2902 }
2903 return false;
2904}
2905
Sebastian Redl82ace982012-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 Blaikieff7d47a2012-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 Redl82ace982012-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).
Craig Topperc3ec1492014-05-26 06:22:03 +00002919 CXXConstructorDecl *Constructor = nullptr;
Sebastian Redl82ace982012-02-11 23:51:08 +00002920 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 Redle5417162012-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 Redl82ace982012-02-11 23:51:08 +00002936 if (ConstructorTmpl)
2937 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00002938 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002939 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002940 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002941 else
2942 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002943 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002944 SuppressUserConversions);
Sebastian Redl82ace982012-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 Redl82ace982012-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 Gregor576e98c2009-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 Gregor576e98c2009-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).
Douglas Gregor4b60a152013-11-07 22:34:54 +00002988///
2989/// \param AllowObjCConversionOnExplicit true if the conversion should
2990/// allow an extra Objective-C pointer conversion on uses of explicit
2991/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00002992static OverloadingResult
2993IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00002994 UserDefinedConversionSequence &User,
2995 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00002996 bool AllowExplicit,
2997 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00002998 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor4b60a152013-11-07 22:34:54 +00002999
Douglas Gregor5ab11652010-04-17 22:01:05 +00003000 // Whether we will only visit constructors.
3001 bool ConstructorsOnly = false;
3002
3003 // If the type we are conversion to is a class type, enumerate its
3004 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003005 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003006 // C++ [over.match.ctor]p1:
3007 // When objects of class type are direct-initialized (8.5), or
3008 // copy-initialized from an expression of the same or a
3009 // derived class type (8.5), overload resolution selects the
3010 // constructor. [...] For copy-initialization, the candidate
3011 // functions are all the converting constructors (12.3.1) of
3012 // that class. The argument list is the expression-list within
3013 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003014 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003015 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00003016 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003017 ConstructorsOnly = true;
3018
Benjamin Kramer90633e32012-11-23 17:04:52 +00003019 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00003020 // RequireCompleteType may have returned true due to some invalid decl
3021 // during template instantiation, but ToType may be complete enough now
3022 // to try to recover.
3023 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003024 // We're not going to find any constructors.
3025 } else if (CXXRecordDecl *ToRecordDecl
3026 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003027
3028 Expr **Args = &From;
3029 unsigned NumArgs = 1;
3030 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003031 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003032 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003033 OverloadingResult Result = IsInitializerListConstructorConversion(
3034 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3035 if (Result != OR_No_Viable_Function)
3036 return Result;
3037 // Never mind.
3038 CandidateSet.clear();
3039
3040 // If we're list-initializing, we pass the individual elements as
3041 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003042 Args = InitList->getInits();
3043 NumArgs = InitList->getNumInits();
3044 ListInitializing = true;
3045 }
3046
David Blaikieff7d47a2012-12-19 00:45:41 +00003047 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3048 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregor89ee6822009-02-28 01:32:25 +00003049 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003050 NamedDecl *D = *Con;
3051 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3052
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003053 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003054 CXXConstructorDecl *Constructor = nullptr;
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003055 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00003056 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003057 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003058 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003059 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3060 else
John McCalla0296f72010-03-19 07:35:19 +00003061 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003062
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003063 bool Usable = !Constructor->isInvalidDecl();
3064 if (ListInitializing)
3065 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3066 else
3067 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3068 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003069 bool SuppressUserConversions = !ConstructorsOnly;
3070 if (SuppressUserConversions && ListInitializing) {
3071 SuppressUserConversions = false;
3072 if (NumArgs == 1) {
3073 // If the first argument is (a reference to) the target type,
3074 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003075 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3076 S.Context, Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003077 }
3078 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003079 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00003080 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003081 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003082 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003083 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003084 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003085 // Allow one user-defined conversion when user specifies a
3086 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00003087 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003088 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003089 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003090 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003091 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003092 }
3093 }
3094
Douglas Gregor5ab11652010-04-17 22:01:05 +00003095 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003096 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003097 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003098 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003099 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003100 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003101 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003102 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3103 // Add all of the conversion functions as candidates.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00003104 std::pair<CXXRecordDecl::conversion_iterator,
3105 CXXRecordDecl::conversion_iterator>
3106 Conversions = FromRecordDecl->getVisibleConversionFunctions();
3107 for (CXXRecordDecl::conversion_iterator
3108 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003109 DeclAccessPair FoundDecl = I.getPair();
3110 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003111 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3112 if (isa<UsingShadowDecl>(D))
3113 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3114
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003115 CXXConversionDecl *Conv;
3116 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003117 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3118 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003119 else
John McCallda4458e2010-03-31 01:36:47 +00003120 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003121
3122 if (AllowExplicit || !Conv->isExplicit()) {
3123 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003124 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3125 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003126 CandidateSet,
3127 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003128 else
John McCall5c32be02010-08-24 20:38:10 +00003129 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003130 From, ToType, CandidateSet,
3131 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003132 }
3133 }
3134 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003135 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003136
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003137 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3138
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003139 OverloadCandidateSet::iterator Best;
Richard Smith48372b62015-01-27 03:30:40 +00003140 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3141 Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003142 case OR_Success:
Richard Smith48372b62015-01-27 03:30:40 +00003143 case OR_Deleted:
John McCall5c32be02010-08-24 20:38:10 +00003144 // Record the standard conversion we used and the conversion function.
3145 if (CXXConstructorDecl *Constructor
3146 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3147 // C++ [over.ics.user]p1:
3148 // If the user-defined conversion is specified by a
3149 // constructor (12.3.1), the initial standard conversion
3150 // sequence converts the source type to the type required by
3151 // the argument of the constructor.
3152 //
3153 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003154 if (isa<InitListExpr>(From)) {
3155 // Initializer lists don't have conversions as such.
3156 User.Before.setAsIdentityConversion();
3157 } else {
3158 if (Best->Conversions[0].isEllipsis())
3159 User.EllipsisConversion = true;
3160 else {
3161 User.Before = Best->Conversions[0].Standard;
3162 User.EllipsisConversion = false;
3163 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003164 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003165 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003166 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003167 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003168 User.After.setAsIdentityConversion();
3169 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3170 User.After.setAllToTypes(ToType);
Richard Smith48372b62015-01-27 03:30:40 +00003171 return Result;
David Blaikie8a40f702012-01-17 06:56:22 +00003172 }
3173 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003174 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3175 // C++ [over.ics.user]p1:
3176 //
3177 // [...] If the user-defined conversion is specified by a
3178 // conversion function (12.3.2), the initial standard
3179 // conversion sequence converts the source type to the
3180 // implicit object parameter of the conversion function.
3181 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003182 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003183 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003184 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003185 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003186
John McCall5c32be02010-08-24 20:38:10 +00003187 // C++ [over.ics.user]p2:
3188 // The second standard conversion sequence converts the
3189 // result of the user-defined conversion to the target type
3190 // for the sequence. Since an implicit conversion sequence
3191 // is an initialization, the special rules for
3192 // initialization by user-defined conversion apply when
3193 // selecting the best user-defined conversion for a
3194 // user-defined conversion sequence (see 13.3.3 and
3195 // 13.3.3.1).
3196 User.After = Best->FinalConversion;
Richard Smith48372b62015-01-27 03:30:40 +00003197 return Result;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003198 }
David Blaikie8a40f702012-01-17 06:56:22 +00003199 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003200
John McCall5c32be02010-08-24 20:38:10 +00003201 case OR_No_Viable_Function:
3202 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003203
John McCall5c32be02010-08-24 20:38:10 +00003204 case OR_Ambiguous:
3205 return OR_Ambiguous;
3206 }
3207
David Blaikie8a40f702012-01-17 06:56:22 +00003208 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003209}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003210
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003211bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003212Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003213 ImplicitConversionSequence ICS;
Richard Smith100b24a2014-04-17 01:52:14 +00003214 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3215 OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003216 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003217 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003218 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003219 if (OvResult == OR_Ambiguous)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003220 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3221 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003222 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003223 if (!RequireCompleteType(From->getLocStart(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003224 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003225 From->getType(), From->getSourceRange()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003226 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3227 << From->getType() << From->getSourceRange() << ToType;
3228 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003229 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003230 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003231 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003232}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003233
Douglas Gregor2837aa22012-02-22 17:32:19 +00003234/// \brief Compare the user-defined conversion functions or constructors
3235/// of two user-defined conversion sequences to determine whether any ordering
3236/// is possible.
3237static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003238compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003239 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003240 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003241 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003242
Douglas Gregor2837aa22012-02-22 17:32:19 +00003243 // Objective-C++:
3244 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003245 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003246 // respectively, always prefer the conversion to a function pointer,
3247 // because the function pointer is more lightweight and is more likely
3248 // to keep code working.
Ted Kremenek8d265c22014-04-01 07:23:18 +00003249 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003250 if (!Conv1)
3251 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003252
Douglas Gregor2837aa22012-02-22 17:32:19 +00003253 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3254 if (!Conv2)
3255 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003256
Douglas Gregor2837aa22012-02-22 17:32:19 +00003257 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3258 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3259 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3260 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003261 return Block1 ? ImplicitConversionSequence::Worse
3262 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003263 }
3264
3265 return ImplicitConversionSequence::Indistinguishable;
3266}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003267
3268static bool hasDeprecatedStringLiteralToCharPtrConversion(
3269 const ImplicitConversionSequence &ICS) {
3270 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3271 (ICS.isUserDefined() &&
3272 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3273}
3274
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003275/// CompareImplicitConversionSequences - Compare two implicit
3276/// conversion sequences to determine whether one is better than the
3277/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003278static ImplicitConversionSequence::CompareKind
3279CompareImplicitConversionSequences(Sema &S,
3280 const ImplicitConversionSequence& ICS1,
3281 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003282{
3283 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3284 // conversion sequences (as defined in 13.3.3.1)
3285 // -- a standard conversion sequence (13.3.3.1.1) is a better
3286 // conversion sequence than a user-defined conversion sequence or
3287 // an ellipsis conversion sequence, and
3288 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3289 // conversion sequence than an ellipsis conversion sequence
3290 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003291 //
John McCall0d1da222010-01-12 00:44:57 +00003292 // C++0x [over.best.ics]p10:
3293 // For the purpose of ranking implicit conversion sequences as
3294 // described in 13.3.3.2, the ambiguous conversion sequence is
3295 // treated as a user-defined sequence that is indistinguishable
3296 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003297
3298 // String literal to 'char *' conversion has been deprecated in C++03. It has
3299 // been removed from C++11. We still accept this conversion, if it happens at
3300 // the best viable function. Otherwise, this conversion is considered worse
3301 // than ellipsis conversion. Consider this as an extension; this is not in the
3302 // standard. For example:
3303 //
3304 // int &f(...); // #1
3305 // void f(char*); // #2
3306 // void g() { int &r = f("foo"); }
3307 //
3308 // In C++03, we pick #2 as the best viable function.
3309 // In C++11, we pick #1 as the best viable function, because ellipsis
3310 // conversion is better than string-literal to char* conversion (since there
3311 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3312 // convert arguments, #2 would be the best viable function in C++11.
3313 // If the best viable function has this conversion, a warning will be issued
3314 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3315
3316 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3317 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3318 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3319 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3320 ? ImplicitConversionSequence::Worse
3321 : ImplicitConversionSequence::Better;
3322
Douglas Gregor5ab11652010-04-17 22:01:05 +00003323 if (ICS1.getKindRank() < ICS2.getKindRank())
3324 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003325 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003326 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003327
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003328 // The following checks require both conversion sequences to be of
3329 // the same kind.
3330 if (ICS1.getKind() != ICS2.getKind())
3331 return ImplicitConversionSequence::Indistinguishable;
3332
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003333 ImplicitConversionSequence::CompareKind Result =
3334 ImplicitConversionSequence::Indistinguishable;
3335
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003336 // Two implicit conversion sequences of the same form are
3337 // indistinguishable conversion sequences unless one of the
3338 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00003339 if (ICS1.isStandard())
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003340 Result = CompareStandardConversionSequences(S,
3341 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003342 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003343 // User-defined conversion sequence U1 is a better conversion
3344 // sequence than another user-defined conversion sequence U2 if
3345 // they contain the same user-defined conversion function or
3346 // constructor and if the second standard conversion sequence of
3347 // U1 is better than the second standard conversion sequence of
3348 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003349 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003350 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003351 Result = CompareStandardConversionSequences(S,
3352 ICS1.UserDefined.After,
3353 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003354 else
3355 Result = compareConversionFunctions(S,
3356 ICS1.UserDefined.ConversionFunction,
3357 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003358 }
3359
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003360 // List-initialization sequence L1 is a better conversion sequence than
3361 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3362 // for some X and L2 does not.
3363 if (Result == ImplicitConversionSequence::Indistinguishable &&
Richard Smitha93f1022013-09-06 22:30:28 +00003364 !ICS1.isBad()) {
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00003365 if (ICS1.isStdInitializerListElement() &&
3366 !ICS2.isStdInitializerListElement())
3367 return ImplicitConversionSequence::Better;
3368 if (!ICS1.isStdInitializerListElement() &&
3369 ICS2.isStdInitializerListElement())
3370 return ImplicitConversionSequence::Worse;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003371 }
3372
3373 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003374}
3375
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003376static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3377 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3378 Qualifiers Quals;
3379 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003380 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003381 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003382
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003383 return Context.hasSameUnqualifiedType(T1, T2);
3384}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003385
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003386// Per 13.3.3.2p3, compare the given standard conversion sequences to
3387// determine if one is a proper subset of the other.
3388static ImplicitConversionSequence::CompareKind
3389compareStandardConversionSubsets(ASTContext &Context,
3390 const StandardConversionSequence& SCS1,
3391 const StandardConversionSequence& SCS2) {
3392 ImplicitConversionSequence::CompareKind Result
3393 = ImplicitConversionSequence::Indistinguishable;
3394
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003395 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003396 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003397 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3398 return ImplicitConversionSequence::Better;
3399 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3400 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003401
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003402 if (SCS1.Second != SCS2.Second) {
3403 if (SCS1.Second == ICK_Identity)
3404 Result = ImplicitConversionSequence::Better;
3405 else if (SCS2.Second == ICK_Identity)
3406 Result = ImplicitConversionSequence::Worse;
3407 else
3408 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003409 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003410 return ImplicitConversionSequence::Indistinguishable;
3411
3412 if (SCS1.Third == SCS2.Third) {
3413 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3414 : ImplicitConversionSequence::Indistinguishable;
3415 }
3416
3417 if (SCS1.Third == ICK_Identity)
3418 return Result == ImplicitConversionSequence::Worse
3419 ? ImplicitConversionSequence::Indistinguishable
3420 : ImplicitConversionSequence::Better;
3421
3422 if (SCS2.Third == ICK_Identity)
3423 return Result == ImplicitConversionSequence::Better
3424 ? ImplicitConversionSequence::Indistinguishable
3425 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003426
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003427 return ImplicitConversionSequence::Indistinguishable;
3428}
3429
Douglas Gregore696ebb2011-01-26 14:52:12 +00003430/// \brief Determine whether one of the given reference bindings is better
3431/// than the other based on what kind of bindings they are.
Richard Smith19172c42014-07-14 02:28:44 +00003432static bool
3433isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3434 const StandardConversionSequence &SCS2) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003435 // C++0x [over.ics.rank]p3b4:
3436 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3437 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003438 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003439 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003440 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003441 // reference*.
3442 //
3443 // FIXME: Rvalue references. We're going rogue with the above edits,
3444 // because the semantics in the current C++0x working paper (N3225 at the
3445 // time of this writing) break the standard definition of std::forward
3446 // and std::reference_wrapper when dealing with references to functions.
3447 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003448 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3449 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3450 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003451
Douglas Gregore696ebb2011-01-26 14:52:12 +00003452 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3453 SCS2.IsLvalueReference) ||
3454 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
Richard Smith19172c42014-07-14 02:28:44 +00003455 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
Douglas Gregore696ebb2011-01-26 14:52:12 +00003456}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003457
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003458/// CompareStandardConversionSequences - Compare two standard
3459/// conversion sequences to determine whether one is better than the
3460/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003461static ImplicitConversionSequence::CompareKind
3462CompareStandardConversionSequences(Sema &S,
3463 const StandardConversionSequence& SCS1,
3464 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003465{
3466 // Standard conversion sequence S1 is a better conversion sequence
3467 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3468
3469 // -- S1 is a proper subsequence of S2 (comparing the conversion
3470 // sequences in the canonical form defined by 13.3.3.1.1,
3471 // excluding any Lvalue Transformation; the identity conversion
3472 // sequence is considered to be a subsequence of any
3473 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003474 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003475 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003476 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003477
3478 // -- the rank of S1 is better than the rank of S2 (by the rules
3479 // defined below), or, if not that,
3480 ImplicitConversionRank Rank1 = SCS1.getRank();
3481 ImplicitConversionRank Rank2 = SCS2.getRank();
3482 if (Rank1 < Rank2)
3483 return ImplicitConversionSequence::Better;
3484 else if (Rank2 < Rank1)
3485 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003486
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003487 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3488 // are indistinguishable unless one of the following rules
3489 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003490
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003491 // A conversion that is not a conversion of a pointer, or
3492 // pointer to member, to bool is better than another conversion
3493 // that is such a conversion.
3494 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3495 return SCS2.isPointerConversionToBool()
3496 ? ImplicitConversionSequence::Better
3497 : ImplicitConversionSequence::Worse;
3498
Douglas Gregor5c407d92008-10-23 00:40:37 +00003499 // C++ [over.ics.rank]p4b2:
3500 //
3501 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003502 // conversion of B* to A* is better than conversion of B* to
3503 // void*, and conversion of A* to void* is better than conversion
3504 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003505 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003506 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003507 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003508 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003509 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3510 // Exactly one of the conversion sequences is a conversion to
3511 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003512 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3513 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003514 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3515 // Neither conversion sequence converts to a void pointer; compare
3516 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003517 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00003518 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003519 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003520 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3521 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003522 // Both conversion sequences are conversions to void
3523 // pointers. Compare the source types to determine if there's an
3524 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003525 QualType FromType1 = SCS1.getFromType();
3526 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003527
3528 // Adjust the types we're converting from via the array-to-pointer
3529 // conversion, if we need to.
3530 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003531 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003532 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003533 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003534
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003535 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3536 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003537
John McCall5c32be02010-08-24 20:38:10 +00003538 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003539 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003540 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003541 return ImplicitConversionSequence::Worse;
3542
3543 // Objective-C++: If one interface is more specific than the
3544 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003545 const ObjCObjectPointerType* FromObjCPtr1
3546 = FromType1->getAs<ObjCObjectPointerType>();
3547 const ObjCObjectPointerType* FromObjCPtr2
3548 = FromType2->getAs<ObjCObjectPointerType>();
3549 if (FromObjCPtr1 && FromObjCPtr2) {
3550 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3551 FromObjCPtr2);
3552 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3553 FromObjCPtr1);
3554 if (AssignLeft != AssignRight) {
3555 return AssignLeft? ImplicitConversionSequence::Better
3556 : ImplicitConversionSequence::Worse;
3557 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003558 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003559 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003560
3561 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3562 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003563 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003564 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003565 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003566
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003567 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003568 // Check for a better reference binding based on the kind of bindings.
3569 if (isBetterReferenceBindingKind(SCS1, SCS2))
3570 return ImplicitConversionSequence::Better;
3571 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3572 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003573
Sebastian Redlb28b4072009-03-22 23:49:27 +00003574 // C++ [over.ics.rank]p3b4:
3575 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3576 // which the references refer are the same type except for
3577 // top-level cv-qualifiers, and the type to which the reference
3578 // initialized by S2 refers is more cv-qualified than the type
3579 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003580 QualType T1 = SCS1.getToType(2);
3581 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003582 T1 = S.Context.getCanonicalType(T1);
3583 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003584 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003585 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3586 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003587 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003588 // Objective-C++ ARC: If the references refer to objects with different
3589 // lifetimes, prefer bindings that don't change lifetime.
3590 if (SCS1.ObjCLifetimeConversionBinding !=
3591 SCS2.ObjCLifetimeConversionBinding) {
3592 return SCS1.ObjCLifetimeConversionBinding
3593 ? ImplicitConversionSequence::Worse
3594 : ImplicitConversionSequence::Better;
3595 }
3596
Chandler Carruth8e543b32010-12-12 08:17:55 +00003597 // If the type is an array type, promote the element qualifiers to the
3598 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003599 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003600 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003601 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003602 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003603 if (T2.isMoreQualifiedThan(T1))
3604 return ImplicitConversionSequence::Better;
3605 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003606 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003607 }
3608 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003609
Francois Pichet08d2fa02011-09-18 21:37:37 +00003610 // In Microsoft mode, prefer an integral conversion to a
3611 // floating-to-integral conversion if the integral conversion
3612 // is between types of the same size.
3613 // For example:
3614 // void f(float);
3615 // void f(int);
3616 // int main {
3617 // long a;
3618 // f(a);
3619 // }
3620 // Here, MSVC will call f(int) instead of generating a compile error
3621 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003622 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3623 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003624 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003625 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003626 return ImplicitConversionSequence::Better;
3627
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003628 return ImplicitConversionSequence::Indistinguishable;
3629}
3630
3631/// CompareQualificationConversions - Compares two standard conversion
3632/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003633/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
Richard Smith17c00b42014-11-12 01:24:00 +00003634static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003635CompareQualificationConversions(Sema &S,
3636 const StandardConversionSequence& SCS1,
3637 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003638 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003639 // -- S1 and S2 differ only in their qualification conversion and
3640 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3641 // cv-qualification signature of type T1 is a proper subset of
3642 // the cv-qualification signature of type T2, and S1 is not the
3643 // deprecated string literal array-to-pointer conversion (4.2).
3644 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3645 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3646 return ImplicitConversionSequence::Indistinguishable;
3647
3648 // FIXME: the example in the standard doesn't use a qualification
3649 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003650 QualType T1 = SCS1.getToType(2);
3651 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003652 T1 = S.Context.getCanonicalType(T1);
3653 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003654 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003655 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3656 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003657
3658 // If the types are the same, we won't learn anything by unwrapped
3659 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003660 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003661 return ImplicitConversionSequence::Indistinguishable;
3662
Chandler Carruth607f38e2009-12-29 07:16:59 +00003663 // If the type is an array type, promote the element qualifiers to the type
3664 // for comparison.
3665 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003666 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003667 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003668 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003669
Mike Stump11289f42009-09-09 15:08:12 +00003670 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003671 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003672
3673 // Objective-C++ ARC:
3674 // Prefer qualification conversions not involving a change in lifetime
3675 // to qualification conversions that do not change lifetime.
3676 if (SCS1.QualificationIncludesObjCLifetime !=
3677 SCS2.QualificationIncludesObjCLifetime) {
3678 Result = SCS1.QualificationIncludesObjCLifetime
3679 ? ImplicitConversionSequence::Worse
3680 : ImplicitConversionSequence::Better;
3681 }
3682
John McCall5c32be02010-08-24 20:38:10 +00003683 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003684 // Within each iteration of the loop, we check the qualifiers to
3685 // determine if this still looks like a qualification
3686 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003687 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003688 // until there are no more pointers or pointers-to-members left
3689 // to unwrap. This essentially mimics what
3690 // IsQualificationConversion does, but here we're checking for a
3691 // strict subset of qualifiers.
3692 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3693 // The qualifiers are the same, so this doesn't tell us anything
3694 // about how the sequences rank.
3695 ;
3696 else if (T2.isMoreQualifiedThan(T1)) {
3697 // T1 has fewer qualifiers, so it could be the better sequence.
3698 if (Result == ImplicitConversionSequence::Worse)
3699 // Neither has qualifiers that are a subset of the other's
3700 // qualifiers.
3701 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003702
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003703 Result = ImplicitConversionSequence::Better;
3704 } else if (T1.isMoreQualifiedThan(T2)) {
3705 // T2 has fewer qualifiers, so it could be the better sequence.
3706 if (Result == ImplicitConversionSequence::Better)
3707 // Neither has qualifiers that are a subset of the other's
3708 // qualifiers.
3709 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003710
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003711 Result = ImplicitConversionSequence::Worse;
3712 } else {
3713 // Qualifiers are disjoint.
3714 return ImplicitConversionSequence::Indistinguishable;
3715 }
3716
3717 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003718 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003719 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003720 }
3721
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003722 // Check that the winning standard conversion sequence isn't using
3723 // the deprecated string literal array to pointer conversion.
3724 switch (Result) {
3725 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003726 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003727 Result = ImplicitConversionSequence::Indistinguishable;
3728 break;
3729
3730 case ImplicitConversionSequence::Indistinguishable:
3731 break;
3732
3733 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003734 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003735 Result = ImplicitConversionSequence::Indistinguishable;
3736 break;
3737 }
3738
3739 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003740}
3741
Douglas Gregor5c407d92008-10-23 00:40:37 +00003742/// CompareDerivedToBaseConversions - Compares two standard conversion
3743/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003744/// various kinds of derived-to-base conversions (C++
3745/// [over.ics.rank]p4b3). As part of these checks, we also look at
3746/// conversions between Objective-C interface types.
Richard Smith17c00b42014-11-12 01:24:00 +00003747static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003748CompareDerivedToBaseConversions(Sema &S,
3749 const StandardConversionSequence& SCS1,
3750 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003751 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003752 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003753 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003754 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003755
3756 // Adjust the types we're converting from via the array-to-pointer
3757 // conversion, if we need to.
3758 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003759 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003760 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003761 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003762
3763 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003764 FromType1 = S.Context.getCanonicalType(FromType1);
3765 ToType1 = S.Context.getCanonicalType(ToType1);
3766 FromType2 = S.Context.getCanonicalType(FromType2);
3767 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003768
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003769 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003770 //
3771 // If class B is derived directly or indirectly from class A and
3772 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003773 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003774 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003775 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003776 SCS2.Second == ICK_Pointer_Conversion &&
3777 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3778 FromType1->isPointerType() && FromType2->isPointerType() &&
3779 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003780 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003781 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003782 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003783 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003784 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003785 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003786 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003787 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003788
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003789 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003790 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003791 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003792 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003793 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003794 return ImplicitConversionSequence::Worse;
3795 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003796
3797 // -- conversion of B* to A* is better than conversion of C* to A*,
3798 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003799 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003800 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003801 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003802 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003803 }
3804 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3805 SCS2.Second == ICK_Pointer_Conversion) {
3806 const ObjCObjectPointerType *FromPtr1
3807 = FromType1->getAs<ObjCObjectPointerType>();
3808 const ObjCObjectPointerType *FromPtr2
3809 = FromType2->getAs<ObjCObjectPointerType>();
3810 const ObjCObjectPointerType *ToPtr1
3811 = ToType1->getAs<ObjCObjectPointerType>();
3812 const ObjCObjectPointerType *ToPtr2
3813 = ToType2->getAs<ObjCObjectPointerType>();
3814
3815 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3816 // Apply the same conversion ranking rules for Objective-C pointer types
3817 // that we do for C++ pointers to class types. However, we employ the
3818 // Objective-C pseudo-subtyping relationship used for assignment of
3819 // Objective-C pointer types.
3820 bool FromAssignLeft
3821 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3822 bool FromAssignRight
3823 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3824 bool ToAssignLeft
3825 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3826 bool ToAssignRight
3827 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3828
3829 // A conversion to an a non-id object pointer type or qualified 'id'
3830 // type is better than a conversion to 'id'.
3831 if (ToPtr1->isObjCIdType() &&
3832 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3833 return ImplicitConversionSequence::Worse;
3834 if (ToPtr2->isObjCIdType() &&
3835 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3836 return ImplicitConversionSequence::Better;
3837
3838 // A conversion to a non-id object pointer type is better than a
3839 // conversion to a qualified 'id' type
3840 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3841 return ImplicitConversionSequence::Worse;
3842 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3843 return ImplicitConversionSequence::Better;
3844
3845 // A conversion to an a non-Class object pointer type or qualified 'Class'
3846 // type is better than a conversion to 'Class'.
3847 if (ToPtr1->isObjCClassType() &&
3848 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3849 return ImplicitConversionSequence::Worse;
3850 if (ToPtr2->isObjCClassType() &&
3851 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3852 return ImplicitConversionSequence::Better;
3853
3854 // A conversion to a non-Class object pointer type is better than a
3855 // conversion to a qualified 'Class' type.
3856 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3857 return ImplicitConversionSequence::Worse;
3858 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3859 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003860
Douglas Gregor058d3de2011-01-31 18:51:41 +00003861 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3862 if (S.Context.hasSameType(FromType1, FromType2) &&
3863 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3864 (ToAssignLeft != ToAssignRight))
3865 return ToAssignLeft? ImplicitConversionSequence::Worse
3866 : ImplicitConversionSequence::Better;
3867
3868 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3869 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3870 (FromAssignLeft != FromAssignRight))
3871 return FromAssignLeft? ImplicitConversionSequence::Better
3872 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003873 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003874 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003875
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003876 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003877 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3878 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3879 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003880 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003881 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003882 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003883 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003884 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003885 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003886 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003887 ToType2->getAs<MemberPointerType>();
3888 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3889 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3890 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3891 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3892 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3893 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3894 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3895 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003896 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003897 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003898 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003899 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003900 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003901 return ImplicitConversionSequence::Better;
3902 }
3903 // conversion of B::* to C::* is better than conversion of A::* to C::*
3904 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003905 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003906 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003907 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003908 return ImplicitConversionSequence::Worse;
3909 }
3910 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003911
Douglas Gregor5ab11652010-04-17 22:01:05 +00003912 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003913 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003914 // -- binding of an expression of type C to a reference of type
3915 // B& is better than binding an expression of type C to a
3916 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003917 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3918 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3919 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003920 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003921 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003922 return ImplicitConversionSequence::Worse;
3923 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003924
Douglas Gregor2fe98832008-11-03 19:09:14 +00003925 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003926 // -- binding of an expression of type B to a reference of type
3927 // A& is better than binding an expression of type C to a
3928 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003929 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3930 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3931 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003932 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003933 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003934 return ImplicitConversionSequence::Worse;
3935 }
3936 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003937
Douglas Gregor5c407d92008-10-23 00:40:37 +00003938 return ImplicitConversionSequence::Indistinguishable;
3939}
3940
Douglas Gregor45bb4832013-03-26 23:36:30 +00003941/// \brief Determine whether the given type is valid, e.g., it is not an invalid
3942/// C++ class.
3943static bool isTypeValid(QualType T) {
3944 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3945 return !Record->isInvalidDecl();
3946
3947 return true;
3948}
3949
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003950/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3951/// determine whether they are reference-related,
3952/// reference-compatible, reference-compatible with added
3953/// qualification, or incompatible, for use in C++ initialization by
3954/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3955/// type, and the first type (T1) is the pointee type of the reference
3956/// type being initialized.
3957Sema::ReferenceCompareResult
3958Sema::CompareReferenceRelationship(SourceLocation Loc,
3959 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003960 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003961 bool &ObjCConversion,
3962 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003963 assert(!OrigT1->isReferenceType() &&
3964 "T1 must be the pointee type of the reference type");
3965 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3966
3967 QualType T1 = Context.getCanonicalType(OrigT1);
3968 QualType T2 = Context.getCanonicalType(OrigT2);
3969 Qualifiers T1Quals, T2Quals;
3970 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3971 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3972
3973 // C++ [dcl.init.ref]p4:
3974 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3975 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3976 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003977 DerivedToBase = false;
3978 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003979 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003980 if (UnqualT1 == UnqualT2) {
3981 // Nothing to do.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003982 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00003983 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
3984 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003985 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003986 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3987 UnqualT2->isObjCObjectOrInterfaceType() &&
3988 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3989 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003990 else
3991 return Ref_Incompatible;
3992
3993 // At this point, we know that T1 and T2 are reference-related (at
3994 // least).
3995
3996 // If the type is an array type, promote the element qualifiers to the type
3997 // for comparison.
3998 if (isa<ArrayType>(T1) && T1Quals)
3999 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4000 if (isa<ArrayType>(T2) && T2Quals)
4001 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4002
4003 // C++ [dcl.init.ref]p4:
4004 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4005 // reference-related to T2 and cv1 is the same cv-qualification
4006 // as, or greater cv-qualification than, cv2. For purposes of
4007 // overload resolution, cases for which cv1 is greater
4008 // cv-qualification than cv2 are identified as
4009 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004010 //
4011 // Note that we also require equivalence of Objective-C GC and address-space
4012 // qualifiers when performing these computations, so that e.g., an int in
4013 // address space 1 is not reference-compatible with an int in address
4014 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004015 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4016 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004017 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4018 ObjCLifetimeConversion = true;
4019
John McCall31168b02011-06-15 23:02:42 +00004020 T1Quals.removeObjCLifetime();
4021 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004022 }
4023
Douglas Gregord517d552011-04-28 17:56:11 +00004024 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004025 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00004026 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004027 return Ref_Compatible_With_Added_Qualification;
4028 else
4029 return Ref_Related;
4030}
4031
Douglas Gregor836a7e82010-08-11 02:15:33 +00004032/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004033/// with DeclType. Return true if something definite is found.
4034static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004035FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4036 QualType DeclType, SourceLocation DeclLoc,
4037 Expr *Init, QualType T2, bool AllowRvalues,
4038 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004039 assert(T2->isRecordType() && "Can only find conversions of record types.");
4040 CXXRecordDecl *T2RecordDecl
4041 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4042
Richard Smith100b24a2014-04-17 01:52:14 +00004043 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00004044 std::pair<CXXRecordDecl::conversion_iterator,
4045 CXXRecordDecl::conversion_iterator>
4046 Conversions = T2RecordDecl->getVisibleConversionFunctions();
4047 for (CXXRecordDecl::conversion_iterator
4048 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004049 NamedDecl *D = *I;
4050 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4051 if (isa<UsingShadowDecl>(D))
4052 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4053
4054 FunctionTemplateDecl *ConvTemplate
4055 = dyn_cast<FunctionTemplateDecl>(D);
4056 CXXConversionDecl *Conv;
4057 if (ConvTemplate)
4058 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4059 else
4060 Conv = cast<CXXConversionDecl>(D);
4061
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004062 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004063 // explicit conversions, skip it.
4064 if (!AllowExplicit && Conv->isExplicit())
4065 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004066
Douglas Gregor836a7e82010-08-11 02:15:33 +00004067 if (AllowRvalues) {
4068 bool DerivedToBase = false;
4069 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004070 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004071
4072 // If we are initializing an rvalue reference, don't permit conversion
4073 // functions that return lvalues.
4074 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4075 const ReferenceType *RefType
4076 = Conv->getConversionType()->getAs<LValueReferenceType>();
4077 if (RefType && !RefType->getPointeeType()->isFunctionType())
4078 continue;
4079 }
4080
Douglas Gregor836a7e82010-08-11 02:15:33 +00004081 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004082 S.CompareReferenceRelationship(
4083 DeclLoc,
4084 Conv->getConversionType().getNonReferenceType()
4085 .getUnqualifiedType(),
4086 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004087 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004088 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004089 continue;
4090 } else {
4091 // If the conversion function doesn't return a reference type,
4092 // it can't be considered for this conversion. An rvalue reference
4093 // is only acceptable if its referencee is a function type.
4094
4095 const ReferenceType *RefType =
4096 Conv->getConversionType()->getAs<ReferenceType>();
4097 if (!RefType ||
4098 (!RefType->isLValueReferenceType() &&
4099 !RefType->getPointeeType()->isFunctionType()))
4100 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004101 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004102
Douglas Gregor836a7e82010-08-11 02:15:33 +00004103 if (ConvTemplate)
4104 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004105 Init, DeclType, CandidateSet,
4106 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004107 else
4108 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004109 DeclType, CandidateSet,
4110 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004111 }
4112
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004113 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4114
Sebastian Redld92badf2010-06-30 18:13:39 +00004115 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004116 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004117 case OR_Success:
4118 // C++ [over.ics.ref]p1:
4119 //
4120 // [...] If the parameter binds directly to the result of
4121 // applying a conversion function to the argument
4122 // expression, the implicit conversion sequence is a
4123 // user-defined conversion sequence (13.3.3.1.2), with the
4124 // second standard conversion sequence either an identity
4125 // conversion or, if the conversion function returns an
4126 // entity of a type that is a derived class of the parameter
4127 // type, a derived-to-base Conversion.
4128 if (!Best->FinalConversion.DirectBinding)
4129 return false;
4130
4131 ICS.setUserDefined();
4132 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4133 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004134 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004135 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004136 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004137 ICS.UserDefined.EllipsisConversion = false;
4138 assert(ICS.UserDefined.After.ReferenceBinding &&
4139 ICS.UserDefined.After.DirectBinding &&
4140 "Expected a direct reference binding!");
4141 return true;
4142
4143 case OR_Ambiguous:
4144 ICS.setAmbiguous();
4145 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4146 Cand != CandidateSet.end(); ++Cand)
4147 if (Cand->Viable)
4148 ICS.Ambiguous.addConversion(Cand->Function);
4149 return true;
4150
4151 case OR_No_Viable_Function:
4152 case OR_Deleted:
4153 // There was no suitable conversion, or we found a deleted
4154 // conversion; continue with other checks.
4155 return false;
4156 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004157
David Blaikie8a40f702012-01-17 06:56:22 +00004158 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004159}
4160
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004161/// \brief Compute an implicit conversion sequence for reference
4162/// initialization.
4163static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004164TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004165 SourceLocation DeclLoc,
4166 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004167 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004168 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4169
4170 // Most paths end in a failed conversion.
4171 ImplicitConversionSequence ICS;
4172 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4173
4174 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4175 QualType T2 = Init->getType();
4176
4177 // If the initializer is the address of an overloaded function, try
4178 // to resolve the overloaded function. If all goes well, T2 is the
4179 // type of the resulting function.
4180 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4181 DeclAccessPair Found;
4182 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4183 false, Found))
4184 T2 = Fn->getType();
4185 }
4186
4187 // Compute some basic properties of the types and the initializer.
4188 bool isRValRef = DeclType->isRValueReferenceType();
4189 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004190 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004191 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004192 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004193 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004194 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004195 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004196
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004197
Sebastian Redld92badf2010-06-30 18:13:39 +00004198 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004199 // A reference to type "cv1 T1" is initialized by an expression
4200 // of type "cv2 T2" as follows:
4201
Sebastian Redld92badf2010-06-30 18:13:39 +00004202 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004203 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004204 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4205 // reference-compatible with "cv2 T2," or
4206 //
4207 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4208 if (InitCategory.isLValue() &&
4209 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004210 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004211 // When a parameter of reference type binds directly (8.5.3)
4212 // to an argument expression, the implicit conversion sequence
4213 // is the identity conversion, unless the argument expression
4214 // has a type that is a derived class of the parameter type,
4215 // in which case the implicit conversion sequence is a
4216 // derived-to-base Conversion (13.3.3.1).
4217 ICS.setStandard();
4218 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004219 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4220 : ObjCConversion? ICK_Compatible_Conversion
4221 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004222 ICS.Standard.Third = ICK_Identity;
4223 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4224 ICS.Standard.setToType(0, T2);
4225 ICS.Standard.setToType(1, T1);
4226 ICS.Standard.setToType(2, T1);
4227 ICS.Standard.ReferenceBinding = true;
4228 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004229 ICS.Standard.IsLvalueReference = !isRValRef;
4230 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4231 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004232 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004233 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004234 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004235 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004236
Sebastian Redld92badf2010-06-30 18:13:39 +00004237 // Nothing more to do: the inaccessibility/ambiguity check for
4238 // derived-to-base conversions is suppressed when we're
4239 // computing the implicit conversion sequence (C++
4240 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004241 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004242 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004243
Sebastian Redld92badf2010-06-30 18:13:39 +00004244 // -- has a class type (i.e., T2 is a class type), where T1 is
4245 // not reference-related to T2, and can be implicitly
4246 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4247 // is reference-compatible with "cv3 T3" 92) (this
4248 // conversion is selected by enumerating the applicable
4249 // conversion functions (13.3.1.6) and choosing the best
4250 // one through overload resolution (13.3)),
4251 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004252 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004253 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004254 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4255 Init, T2, /*AllowRvalues=*/false,
4256 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004257 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004258 }
4259 }
4260
Sebastian Redld92badf2010-06-30 18:13:39 +00004261 // -- Otherwise, the reference shall be an lvalue reference to a
4262 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004263 // shall be an rvalue reference.
Richard Smithce4f6082012-05-24 04:29:20 +00004264 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004265 return ICS;
4266
Douglas Gregorf143cd52011-01-24 16:14:37 +00004267 // -- If the initializer expression
4268 //
4269 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004270 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004271 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4272 (InitCategory.isXValue() ||
4273 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4274 (InitCategory.isLValue() && T2->isFunctionType()))) {
4275 ICS.setStandard();
4276 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004277 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004278 : ObjCConversion? ICK_Compatible_Conversion
4279 : ICK_Identity;
4280 ICS.Standard.Third = ICK_Identity;
4281 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4282 ICS.Standard.setToType(0, T2);
4283 ICS.Standard.setToType(1, T1);
4284 ICS.Standard.setToType(2, T1);
4285 ICS.Standard.ReferenceBinding = true;
4286 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4287 // binding unless we're binding to a class prvalue.
4288 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4289 // allow the use of rvalue references in C++98/03 for the benefit of
4290 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004291 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004292 S.getLangOpts().CPlusPlus11 ||
Richard Smithb94afe12014-07-14 19:54:05 +00004293 !(InitCategory.isPRValue() || T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004294 ICS.Standard.IsLvalueReference = !isRValRef;
4295 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004296 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004297 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004298 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004299 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004300 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004301 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004302 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004303
Douglas Gregorf143cd52011-01-24 16:14:37 +00004304 // -- has a class type (i.e., T2 is a class type), where T1 is not
4305 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004306 // an xvalue, class prvalue, or function lvalue of type
4307 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004308 // "cv3 T3",
4309 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004310 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004311 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004312 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004313 // class subobject).
4314 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004315 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004316 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4317 Init, T2, /*AllowRvalues=*/true,
4318 AllowExplicit)) {
4319 // In the second case, if the reference is an rvalue reference
4320 // and the second standard conversion sequence of the
4321 // user-defined conversion sequence includes an lvalue-to-rvalue
4322 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004323 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004324 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4325 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4326
Douglas Gregor95273c32011-01-21 16:36:05 +00004327 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004328 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004329
Richard Smith19172c42014-07-14 02:28:44 +00004330 // A temporary of function type cannot be created; don't even try.
4331 if (T1->isFunctionType())
4332 return ICS;
4333
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004334 // -- Otherwise, a temporary of type "cv1 T1" is created and
4335 // initialized from the initializer expression using the
4336 // rules for a non-reference copy initialization (8.5). The
4337 // reference is then bound to the temporary. If T1 is
4338 // reference-related to T2, cv1 must be the same
4339 // cv-qualification as, or greater cv-qualification than,
4340 // cv2; otherwise, the program is ill-formed.
4341 if (RefRelationship == Sema::Ref_Related) {
4342 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4343 // we would be reference-compatible or reference-compatible with
4344 // added qualification. But that wasn't the case, so the reference
4345 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004346 //
4347 // Note that we only want to check address spaces and cvr-qualifiers here.
4348 // ObjC GC and lifetime qualifiers aren't important.
4349 Qualifiers T1Quals = T1.getQualifiers();
4350 Qualifiers T2Quals = T2.getQualifiers();
4351 T1Quals.removeObjCGCAttr();
4352 T1Quals.removeObjCLifetime();
4353 T2Quals.removeObjCGCAttr();
4354 T2Quals.removeObjCLifetime();
4355 if (!T1Quals.compatiblyIncludes(T2Quals))
4356 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004357 }
4358
4359 // If at least one of the types is a class type, the types are not
4360 // related, and we aren't allowed any user conversions, the
4361 // reference binding fails. This case is important for breaking
4362 // recursion, since TryImplicitConversion below will attempt to
4363 // create a temporary through the use of a copy constructor.
4364 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4365 (T1->isRecordType() || T2->isRecordType()))
4366 return ICS;
4367
Douglas Gregorcba72b12011-01-21 05:18:22 +00004368 // If T1 is reference-related to T2 and the reference is an rvalue
4369 // reference, the initializer expression shall not be an lvalue.
4370 if (RefRelationship >= Sema::Ref_Related &&
4371 isRValRef && Init->Classify(S.Context).isLValue())
4372 return ICS;
4373
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004374 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004375 // When a parameter of reference type is not bound directly to
4376 // an argument expression, the conversion sequence is the one
4377 // required to convert the argument expression to the
4378 // underlying type of the reference according to
4379 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4380 // to copy-initializing a temporary of the underlying type with
4381 // the argument expression. Any difference in top-level
4382 // cv-qualification is subsumed by the initialization itself
4383 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004384 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4385 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004386 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004387 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004388 /*AllowObjCWritebackConversion=*/false,
4389 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004390
4391 // Of course, that's still a reference binding.
4392 if (ICS.isStandard()) {
4393 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004394 ICS.Standard.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004395 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004396 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004397 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004398 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004399 } else if (ICS.isUserDefined()) {
Richard Smith19172c42014-07-14 02:28:44 +00004400 const ReferenceType *LValRefType =
4401 ICS.UserDefined.ConversionFunction->getReturnType()
4402 ->getAs<LValueReferenceType>();
4403
4404 // C++ [over.ics.ref]p3:
4405 // Except for an implicit object parameter, for which see 13.3.1, a
4406 // standard conversion sequence cannot be formed if it requires [...]
4407 // binding an rvalue reference to an lvalue other than a function
4408 // lvalue.
4409 // Note that the function case is not possible here.
4410 if (DeclType->isRValueReferenceType() && LValRefType) {
4411 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4412 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4413 // reference to an rvalue!
4414 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4415 return ICS;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004416 }
Richard Smith19172c42014-07-14 02:28:44 +00004417
Ismail Pazarbasi99afd962014-01-24 10:54:12 +00004418 ICS.UserDefined.Before.setAsIdentityConversion();
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004419 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004420 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004421 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4422 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004423 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4424 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004425 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004426
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004427 return ICS;
4428}
4429
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004430static ImplicitConversionSequence
4431TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4432 bool SuppressUserConversions,
4433 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004434 bool AllowObjCWritebackConversion,
4435 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004436
4437/// TryListConversion - Try to copy-initialize a value of type ToType from the
4438/// initializer list From.
4439static ImplicitConversionSequence
4440TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4441 bool SuppressUserConversions,
4442 bool InOverloadResolution,
4443 bool AllowObjCWritebackConversion) {
4444 // C++11 [over.ics.list]p1:
4445 // When an argument is an initializer list, it is not an expression and
4446 // special rules apply for converting it to a parameter type.
4447
4448 ImplicitConversionSequence Result;
4449 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4450
Sebastian Redl09edce02012-01-23 22:09:39 +00004451 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004452 // initialized from init lists.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004453 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004454 return Result;
4455
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004456 // C++11 [over.ics.list]p2:
4457 // If the parameter type is std::initializer_list<X> or "array of X" and
4458 // all the elements can be implicitly converted to X, the implicit
4459 // conversion sequence is the worst conversion necessary to convert an
4460 // element of the list to X.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004461 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004462 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004463 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004464 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004465 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004466 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004467 if (!X.isNull()) {
4468 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4469 Expr *Init = From->getInit(i);
4470 ImplicitConversionSequence ICS =
4471 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4472 InOverloadResolution,
4473 AllowObjCWritebackConversion);
4474 // If a single element isn't convertible, fail.
4475 if (ICS.isBad()) {
4476 Result = ICS;
4477 break;
4478 }
4479 // Otherwise, look for the worst conversion.
4480 if (Result.isBad() ||
4481 CompareImplicitConversionSequences(S, ICS, Result) ==
4482 ImplicitConversionSequence::Worse)
4483 Result = ICS;
4484 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004485
4486 // For an empty list, we won't have computed any conversion sequence.
4487 // Introduce the identity conversion sequence.
4488 if (From->getNumInits() == 0) {
4489 Result.setStandard();
4490 Result.Standard.setAsIdentityConversion();
4491 Result.Standard.setFromType(ToType);
4492 Result.Standard.setAllToTypes(ToType);
4493 }
4494
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004495 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004496 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004497 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004498
4499 // C++11 [over.ics.list]p3:
4500 // Otherwise, if the parameter is a non-aggregate class X and overload
4501 // resolution chooses a single best constructor [...] the implicit
4502 // conversion sequence is a user-defined conversion sequence. If multiple
4503 // constructors are viable but none is better than the others, the
4504 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004505 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4506 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004507 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4508 /*AllowExplicit=*/false,
4509 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004510 AllowObjCWritebackConversion,
4511 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004512 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004513
4514 // C++11 [over.ics.list]p4:
4515 // Otherwise, if the parameter has an aggregate type which can be
4516 // initialized from the initializer list [...] the implicit conversion
4517 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004518 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004519 // Type is an aggregate, argument is an init list. At this point it comes
4520 // down to checking whether the initialization works.
4521 // FIXME: Find out whether this parameter is consumed or not.
4522 InitializedEntity Entity =
4523 InitializedEntity::InitializeParameter(S.Context, ToType,
4524 /*Consumed=*/false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004525 if (S.CanPerformCopyInitialization(Entity, From)) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004526 Result.setUserDefined();
4527 Result.UserDefined.Before.setAsIdentityConversion();
4528 // Initializer lists don't have a type.
4529 Result.UserDefined.Before.setFromType(QualType());
4530 Result.UserDefined.Before.setAllToTypes(QualType());
4531
4532 Result.UserDefined.After.setAsIdentityConversion();
4533 Result.UserDefined.After.setFromType(ToType);
4534 Result.UserDefined.After.setAllToTypes(ToType);
Craig Topperc3ec1492014-05-26 06:22:03 +00004535 Result.UserDefined.ConversionFunction = nullptr;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004536 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004537 return Result;
4538 }
4539
4540 // C++11 [over.ics.list]p5:
4541 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004542 if (ToType->isReferenceType()) {
4543 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4544 // mention initializer lists in any way. So we go by what list-
4545 // initialization would do and try to extrapolate from that.
4546
4547 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4548
4549 // If the initializer list has a single element that is reference-related
4550 // to the parameter type, we initialize the reference from that.
4551 if (From->getNumInits() == 1) {
4552 Expr *Init = From->getInit(0);
4553
4554 QualType T2 = Init->getType();
4555
4556 // If the initializer is the address of an overloaded function, try
4557 // to resolve the overloaded function. If all goes well, T2 is the
4558 // type of the resulting function.
4559 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4560 DeclAccessPair Found;
4561 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4562 Init, ToType, false, Found))
4563 T2 = Fn->getType();
4564 }
4565
4566 // Compute some basic properties of the types and the initializer.
4567 bool dummy1 = false;
4568 bool dummy2 = false;
4569 bool dummy3 = false;
4570 Sema::ReferenceCompareResult RefRelationship
4571 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4572 dummy2, dummy3);
4573
Richard Smith4d2bbd72013-09-06 01:22:42 +00004574 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004575 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4576 SuppressUserConversions,
4577 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004578 }
Sebastian Redldf888642011-12-03 14:54:30 +00004579 }
4580
4581 // Otherwise, we bind the reference to a temporary created from the
4582 // initializer list.
4583 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4584 InOverloadResolution,
4585 AllowObjCWritebackConversion);
4586 if (Result.isFailure())
4587 return Result;
4588 assert(!Result.isEllipsis() &&
4589 "Sub-initialization cannot result in ellipsis conversion.");
4590
4591 // Can we even bind to a temporary?
4592 if (ToType->isRValueReferenceType() ||
4593 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4594 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4595 Result.UserDefined.After;
4596 SCS.ReferenceBinding = true;
4597 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4598 SCS.BindsToRvalue = true;
4599 SCS.BindsToFunctionLvalue = false;
4600 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4601 SCS.ObjCLifetimeConversionBinding = false;
4602 } else
4603 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4604 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004605 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004606 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004607
4608 // C++11 [over.ics.list]p6:
4609 // Otherwise, if the parameter type is not a class:
4610 if (!ToType->isRecordType()) {
4611 // - if the initializer list has one element, the implicit conversion
4612 // sequence is the one required to convert the element to the
4613 // parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004614 unsigned NumInits = From->getNumInits();
4615 if (NumInits == 1)
4616 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4617 SuppressUserConversions,
4618 InOverloadResolution,
4619 AllowObjCWritebackConversion);
4620 // - if the initializer list has no elements, the implicit conversion
4621 // sequence is the identity conversion.
4622 else if (NumInits == 0) {
4623 Result.setStandard();
4624 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004625 Result.Standard.setFromType(ToType);
4626 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004627 }
4628 return Result;
4629 }
4630
4631 // C++11 [over.ics.list]p7:
4632 // In all cases other than those enumerated above, no conversion is possible
4633 return Result;
4634}
4635
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004636/// TryCopyInitialization - Try to copy-initialize a value of type
4637/// ToType from the expression From. Return the implicit conversion
4638/// sequence required to pass this argument, which may be a bad
4639/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004640/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004641/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004642static ImplicitConversionSequence
4643TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004644 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004645 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004646 bool AllowObjCWritebackConversion,
4647 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004648 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4649 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4650 InOverloadResolution,AllowObjCWritebackConversion);
4651
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004652 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004653 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004654 /*FIXME:*/From->getLocStart(),
4655 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004656 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004657
John McCall5c32be02010-08-24 20:38:10 +00004658 return TryImplicitConversion(S, From, ToType,
4659 SuppressUserConversions,
4660 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004661 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004662 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004663 AllowObjCWritebackConversion,
4664 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004665}
4666
Anna Zaks1b068122011-07-28 19:46:48 +00004667static bool TryCopyInitialization(const CanQualType FromQTy,
4668 const CanQualType ToQTy,
4669 Sema &S,
4670 SourceLocation Loc,
4671 ExprValueKind FromVK) {
4672 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4673 ImplicitConversionSequence ICS =
4674 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4675
4676 return !ICS.isBad();
4677}
4678
Douglas Gregor436424c2008-11-18 23:14:02 +00004679/// TryObjectArgumentInitialization - Try to initialize the object
4680/// parameter of the given member function (@c Method) from the
4681/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004682static ImplicitConversionSequence
Richard Smith03c66d32013-01-26 02:07:32 +00004683TryObjectArgumentInitialization(Sema &S, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004684 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004685 CXXMethodDecl *Method,
4686 CXXRecordDecl *ActingContext) {
4687 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004688 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4689 // const volatile object.
4690 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4691 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004692 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004693
4694 // Set up the conversion sequence as a "bad" conversion, to allow us
4695 // to exit early.
4696 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004697
4698 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00004699 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004700 FromType = PT->getPointeeType();
4701
Douglas Gregor02824322011-01-26 19:30:28 +00004702 // When we had a pointer, it's implicitly dereferenced, so we
4703 // better have an lvalue.
4704 assert(FromClassification.isLValue());
4705 }
4706
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004707 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004708
Douglas Gregor02824322011-01-26 19:30:28 +00004709 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004710 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004711 // parameter is
4712 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004713 // - "lvalue reference to cv X" for functions declared without a
4714 // ref-qualifier or with the & ref-qualifier
4715 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004716 // ref-qualifier
4717 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004718 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004719 // cv-qualification on the member function declaration.
4720 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004721 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004722 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004723 // (C++ [over.match.funcs]p5). We perform a simplified version of
4724 // reference binding here, that allows class rvalues to bind to
4725 // non-constant references.
4726
Douglas Gregor02824322011-01-26 19:30:28 +00004727 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004728 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004729 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004730 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004731 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004732 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00004733 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004734 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004735 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004736
4737 // Check that we have either the same type or a derived type. It
4738 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004739 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004740 ImplicitConversionKind SecondKind;
4741 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4742 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004743 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004744 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004745 else {
John McCall65eb8792010-02-25 01:37:24 +00004746 ICS.setBad(BadConversionSequence::unrelated_class,
4747 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004748 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004749 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004750
Douglas Gregor02824322011-01-26 19:30:28 +00004751 // Check the ref-qualifier.
4752 switch (Method->getRefQualifier()) {
4753 case RQ_None:
4754 // Do nothing; we don't care about lvalueness or rvalueness.
4755 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004756
Douglas Gregor02824322011-01-26 19:30:28 +00004757 case RQ_LValue:
4758 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4759 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004760 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004761 ImplicitParamType);
4762 return ICS;
4763 }
4764 break;
4765
4766 case RQ_RValue:
4767 if (!FromClassification.isRValue()) {
4768 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004769 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004770 ImplicitParamType);
4771 return ICS;
4772 }
4773 break;
4774 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004775
Douglas Gregor436424c2008-11-18 23:14:02 +00004776 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004777 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004778 ICS.Standard.setAsIdentityConversion();
4779 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004780 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004781 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004782 ICS.Standard.ReferenceBinding = true;
4783 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004784 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004785 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004786 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4787 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4788 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004789 return ICS;
4790}
4791
4792/// PerformObjectArgumentInitialization - Perform initialization of
4793/// the implicit object parameter for the given Method with the given
4794/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004795ExprResult
4796Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004797 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004798 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004799 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004800 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004801 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004802 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004803
Douglas Gregor02824322011-01-26 19:30:28 +00004804 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004805 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004806 FromRecordType = PT->getPointeeType();
4807 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004808 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004809 } else {
4810 FromRecordType = From->getType();
4811 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004812 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004813 }
4814
John McCall6e9f8f62009-12-03 04:06:58 +00004815 // Note that we always use the true parent context when performing
4816 // the actual argument initialization.
Nico Weberb58e51c2014-11-19 05:21:39 +00004817 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
4818 *this, From->getType(), FromClassification, Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004819 if (ICS.isBad()) {
4820 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4821 Qualifiers FromQs = FromRecordType.getQualifiers();
4822 Qualifiers ToQs = DestType.getQualifiers();
4823 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4824 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004825 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004826 diag::err_member_function_call_bad_cvr)
4827 << Method->getDeclName() << FromRecordType << (CVR - 1)
4828 << From->getSourceRange();
4829 Diag(Method->getLocation(), diag::note_previous_decl)
4830 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004831 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004832 }
4833 }
4834
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004835 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004836 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004837 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004838 }
Mike Stump11289f42009-09-09 15:08:12 +00004839
John Wiegley01296292011-04-08 18:41:53 +00004840 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4841 ExprResult FromRes =
4842 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4843 if (FromRes.isInvalid())
4844 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004845 From = FromRes.get();
John Wiegley01296292011-04-08 18:41:53 +00004846 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004847
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004848 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004849 From = ImpCastExprToType(From, DestType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004850 From->getValueKind()).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004851 return From;
Douglas Gregor436424c2008-11-18 23:14:02 +00004852}
4853
Douglas Gregor5fb53972009-01-14 15:45:31 +00004854/// TryContextuallyConvertToBool - Attempt to contextually convert the
4855/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004856static ImplicitConversionSequence
4857TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00004858 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004859 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004860 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004861 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004862 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004863 /*AllowObjCWritebackConversion=*/false,
4864 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004865}
4866
4867/// PerformContextuallyConvertToBool - Perform a contextual conversion
4868/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004869ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004870 if (checkPlaceholderForOverload(*this, From))
4871 return ExprError();
4872
John McCall5c32be02010-08-24 20:38:10 +00004873 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004874 if (!ICS.isBad())
4875 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004876
Fariborz Jahanian76197412009-11-18 18:26:29 +00004877 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004878 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00004879 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004880 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004881 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004882}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004883
Richard Smithf8379a02012-01-18 23:55:52 +00004884/// Check that the specified conversion is permitted in a converted constant
4885/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4886/// is acceptable.
4887static bool CheckConvertedConstantConversions(Sema &S,
4888 StandardConversionSequence &SCS) {
4889 // Since we know that the target type is an integral or unscoped enumeration
4890 // type, most conversion kinds are impossible. All possible First and Third
4891 // conversions are fine.
4892 switch (SCS.Second) {
4893 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00004894 case ICK_NoReturn_Adjustment:
Richard Smithf8379a02012-01-18 23:55:52 +00004895 case ICK_Integral_Promotion:
Richard Smith410cc892014-11-26 03:26:53 +00004896 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
Richard Smithf8379a02012-01-18 23:55:52 +00004897 return true;
4898
4899 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00004900 // Conversion from an integral or unscoped enumeration type to bool is
Richard Smith410cc892014-11-26 03:26:53 +00004901 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
4902 // conversion, so we allow it in a converted constant expression.
4903 //
4904 // FIXME: Per core issue 1407, we should not allow this, but that breaks
4905 // a lot of popular code. We should at least add a warning for this
4906 // (non-conforming) extension.
Richard Smithca24ed42012-09-13 22:00:12 +00004907 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4908 SCS.getToType(2)->isBooleanType();
4909
Richard Smith410cc892014-11-26 03:26:53 +00004910 case ICK_Pointer_Conversion:
4911 case ICK_Pointer_Member:
4912 // C++1z: null pointer conversions and null member pointer conversions are
4913 // only permitted if the source type is std::nullptr_t.
4914 return SCS.getFromType()->isNullPtrType();
4915
4916 case ICK_Floating_Promotion:
4917 case ICK_Complex_Promotion:
4918 case ICK_Floating_Conversion:
4919 case ICK_Complex_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00004920 case ICK_Floating_Integral:
Richard Smith410cc892014-11-26 03:26:53 +00004921 case ICK_Compatible_Conversion:
4922 case ICK_Derived_To_Base:
4923 case ICK_Vector_Conversion:
4924 case ICK_Vector_Splat:
Richard Smithf8379a02012-01-18 23:55:52 +00004925 case ICK_Complex_Real:
Richard Smith410cc892014-11-26 03:26:53 +00004926 case ICK_Block_Pointer_Conversion:
4927 case ICK_TransparentUnionConversion:
4928 case ICK_Writeback_Conversion:
4929 case ICK_Zero_Event_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00004930 return false;
4931
4932 case ICK_Lvalue_To_Rvalue:
4933 case ICK_Array_To_Pointer:
4934 case ICK_Function_To_Pointer:
Richard Smith410cc892014-11-26 03:26:53 +00004935 llvm_unreachable("found a first conversion kind in Second");
4936
Richard Smithf8379a02012-01-18 23:55:52 +00004937 case ICK_Qualification:
Richard Smith410cc892014-11-26 03:26:53 +00004938 llvm_unreachable("found a third conversion kind in Second");
Richard Smithf8379a02012-01-18 23:55:52 +00004939
4940 case ICK_Num_Conversion_Kinds:
4941 break;
4942 }
4943
4944 llvm_unreachable("unknown conversion kind");
4945}
4946
4947/// CheckConvertedConstantExpression - Check that the expression From is a
4948/// converted constant expression of type T, perform the conversion and produce
4949/// the converted expression, per C++11 [expr.const]p3.
Richard Smith410cc892014-11-26 03:26:53 +00004950static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
4951 QualType T, APValue &Value,
4952 Sema::CCEKind CCE,
4953 bool RequireInt) {
4954 assert(S.getLangOpts().CPlusPlus11 &&
4955 "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00004956
Richard Smith410cc892014-11-26 03:26:53 +00004957 if (checkPlaceholderForOverload(S, From))
Richard Smithf8379a02012-01-18 23:55:52 +00004958 return ExprError();
4959
Richard Smith410cc892014-11-26 03:26:53 +00004960 // C++1z [expr.const]p3:
4961 // A converted constant expression of type T is an expression,
4962 // implicitly converted to type T, where the converted
4963 // expression is a constant expression and the implicit conversion
4964 // sequence contains only [... list of conversions ...].
Richard Smithf8379a02012-01-18 23:55:52 +00004965 ImplicitConversionSequence ICS =
Richard Smith410cc892014-11-26 03:26:53 +00004966 TryCopyInitialization(S, From, T,
Richard Smithf8379a02012-01-18 23:55:52 +00004967 /*SuppressUserConversions=*/false,
Richard Smithf8379a02012-01-18 23:55:52 +00004968 /*InOverloadResolution=*/false,
Richard Smith410cc892014-11-26 03:26:53 +00004969 /*AllowObjcWritebackConversion=*/false,
4970 /*AllowExplicit=*/false);
Craig Topperc3ec1492014-05-26 06:22:03 +00004971 StandardConversionSequence *SCS = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +00004972 switch (ICS.getKind()) {
4973 case ImplicitConversionSequence::StandardConversion:
Richard Smithf8379a02012-01-18 23:55:52 +00004974 SCS = &ICS.Standard;
4975 break;
4976 case ImplicitConversionSequence::UserDefinedConversion:
Richard Smith410cc892014-11-26 03:26:53 +00004977 // We are converting to a non-class type, so the Before sequence
4978 // must be trivial.
Richard Smithf8379a02012-01-18 23:55:52 +00004979 SCS = &ICS.UserDefined.After;
4980 break;
4981 case ImplicitConversionSequence::AmbiguousConversion:
4982 case ImplicitConversionSequence::BadConversion:
Richard Smith410cc892014-11-26 03:26:53 +00004983 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
4984 return S.Diag(From->getLocStart(),
4985 diag::err_typecheck_converted_constant_expression)
4986 << From->getType() << From->getSourceRange() << T;
Richard Smithf8379a02012-01-18 23:55:52 +00004987 return ExprError();
4988
4989 case ImplicitConversionSequence::EllipsisConversion:
4990 llvm_unreachable("ellipsis conversion in converted constant expression");
4991 }
4992
Richard Smith410cc892014-11-26 03:26:53 +00004993 // Check that we would only use permitted conversions.
4994 if (!CheckConvertedConstantConversions(S, *SCS)) {
4995 return S.Diag(From->getLocStart(),
4996 diag::err_typecheck_converted_constant_expression_disallowed)
4997 << From->getType() << From->getSourceRange() << T;
4998 }
4999 // [...] and where the reference binding (if any) binds directly.
5000 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5001 return S.Diag(From->getLocStart(),
5002 diag::err_typecheck_converted_constant_expression_indirect)
5003 << From->getType() << From->getSourceRange() << T;
5004 }
5005
5006 ExprResult Result =
5007 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
Richard Smithf8379a02012-01-18 23:55:52 +00005008 if (Result.isInvalid())
5009 return Result;
5010
5011 // Check for a narrowing implicit conversion.
5012 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005013 QualType PreNarrowingType;
Richard Smith410cc892014-11-26 03:26:53 +00005014 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
Richard Smith5614ca72012-03-23 23:55:39 +00005015 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00005016 case NK_Variable_Narrowing:
5017 // Implicit conversion to a narrower type, and the value is not a constant
5018 // expression. We'll diagnose this in a moment.
5019 case NK_Not_Narrowing:
5020 break;
5021
5022 case NK_Constant_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005023 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005024 << CCE << /*Constant*/1
Richard Smith410cc892014-11-26 03:26:53 +00005025 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005026 break;
5027
5028 case NK_Type_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005029 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005030 << CCE << /*Constant*/0 << From->getType() << T;
5031 break;
5032 }
5033
5034 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005035 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005036 Expr::EvalResult Eval;
5037 Eval.Diag = &Notes;
5038
Richard Smith410cc892014-11-26 03:26:53 +00005039 if ((T->isReferenceType()
5040 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5041 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5042 (RequireInt && !Eval.Val.isInt())) {
Richard Smithf8379a02012-01-18 23:55:52 +00005043 // The expression can't be folded, so we can't keep it at this position in
5044 // the AST.
5045 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005046 } else {
Richard Smith410cc892014-11-26 03:26:53 +00005047 Value = Eval.Val;
Richard Smith911e1422012-01-30 22:27:01 +00005048
5049 if (Notes.empty()) {
5050 // It's a constant expression.
5051 return Result;
5052 }
Richard Smithf8379a02012-01-18 23:55:52 +00005053 }
5054
5055 // It's not a constant expression. Produce an appropriate diagnostic.
5056 if (Notes.size() == 1 &&
5057 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
Richard Smith410cc892014-11-26 03:26:53 +00005058 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
Richard Smithf8379a02012-01-18 23:55:52 +00005059 else {
Richard Smith410cc892014-11-26 03:26:53 +00005060 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005061 << CCE << From->getSourceRange();
5062 for (unsigned I = 0; I < Notes.size(); ++I)
Richard Smith410cc892014-11-26 03:26:53 +00005063 S.Diag(Notes[I].first, Notes[I].second);
Richard Smithf8379a02012-01-18 23:55:52 +00005064 }
Richard Smith410cc892014-11-26 03:26:53 +00005065 return ExprError();
Richard Smithf8379a02012-01-18 23:55:52 +00005066}
5067
Richard Smith410cc892014-11-26 03:26:53 +00005068ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5069 APValue &Value, CCEKind CCE) {
5070 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5071}
5072
5073ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5074 llvm::APSInt &Value,
5075 CCEKind CCE) {
5076 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5077
5078 APValue V;
5079 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5080 if (!R.isInvalid())
5081 Value = V.getInt();
5082 return R;
5083}
5084
5085
John McCallfec112d2011-09-09 06:11:02 +00005086/// dropPointerConversions - If the given standard conversion sequence
5087/// involves any pointer conversions, remove them. This may change
5088/// the result type of the conversion sequence.
5089static void dropPointerConversion(StandardConversionSequence &SCS) {
5090 if (SCS.Second == ICK_Pointer_Conversion) {
5091 SCS.Second = ICK_Identity;
5092 SCS.Third = ICK_Identity;
5093 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5094 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005095}
John McCall5c32be02010-08-24 20:38:10 +00005096
John McCallfec112d2011-09-09 06:11:02 +00005097/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5098/// convert the expression From to an Objective-C pointer type.
5099static ImplicitConversionSequence
5100TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5101 // Do an implicit conversion to 'id'.
5102 QualType Ty = S.Context.getObjCIdType();
5103 ImplicitConversionSequence ICS
5104 = TryImplicitConversion(S, From, Ty,
5105 // FIXME: Are these flags correct?
5106 /*SuppressUserConversions=*/false,
5107 /*AllowExplicit=*/true,
5108 /*InOverloadResolution=*/false,
5109 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005110 /*AllowObjCWritebackConversion=*/false,
5111 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005112
5113 // Strip off any final conversions to 'id'.
5114 switch (ICS.getKind()) {
5115 case ImplicitConversionSequence::BadConversion:
5116 case ImplicitConversionSequence::AmbiguousConversion:
5117 case ImplicitConversionSequence::EllipsisConversion:
5118 break;
5119
5120 case ImplicitConversionSequence::UserDefinedConversion:
5121 dropPointerConversion(ICS.UserDefined.After);
5122 break;
5123
5124 case ImplicitConversionSequence::StandardConversion:
5125 dropPointerConversion(ICS.Standard);
5126 break;
5127 }
5128
5129 return ICS;
5130}
5131
5132/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5133/// conversion of the expression From to an Objective-C pointer type.
5134ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005135 if (checkPlaceholderForOverload(*this, From))
5136 return ExprError();
5137
John McCall8b07ec22010-05-15 11:32:37 +00005138 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005139 ImplicitConversionSequence ICS =
5140 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005141 if (!ICS.isBad())
5142 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005143 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005144}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005145
Richard Smith8dd34252012-02-04 07:07:42 +00005146/// Determine whether the provided type is an integral type, or an enumeration
5147/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005148bool Sema::ICEConvertDiagnoser::match(QualType T) {
5149 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5150 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005151}
5152
Larisse Voufo236bec22013-06-10 06:50:24 +00005153static ExprResult
5154diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5155 Sema::ContextualImplicitConverter &Converter,
5156 QualType T, UnresolvedSetImpl &ViableConversions) {
5157
5158 if (Converter.Suppress)
5159 return ExprError();
5160
5161 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5162 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5163 CXXConversionDecl *Conv =
5164 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5165 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5166 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5167 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005168 return From;
Larisse Voufo236bec22013-06-10 06:50:24 +00005169}
5170
5171static bool
5172diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5173 Sema::ContextualImplicitConverter &Converter,
5174 QualType T, bool HadMultipleCandidates,
5175 UnresolvedSetImpl &ExplicitConversions) {
5176 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5177 DeclAccessPair Found = ExplicitConversions[0];
5178 CXXConversionDecl *Conversion =
5179 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5180
5181 // The user probably meant to invoke the given explicit
5182 // conversion; use it.
5183 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5184 std::string TypeStr;
5185 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5186
5187 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5188 << FixItHint::CreateInsertion(From->getLocStart(),
5189 "static_cast<" + TypeStr + ">(")
5190 << FixItHint::CreateInsertion(
Alp Tokerb6cc5922014-05-03 03:45:55 +00005191 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
Larisse Voufo236bec22013-06-10 06:50:24 +00005192 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5193
5194 // If we aren't in a SFINAE context, build a call to the
5195 // explicit conversion function.
5196 if (SemaRef.isSFINAEContext())
5197 return true;
5198
Craig Topperc3ec1492014-05-26 06:22:03 +00005199 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005200 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5201 HadMultipleCandidates);
5202 if (Result.isInvalid())
5203 return true;
5204 // Record usage of conversion in an implicit cast.
5205 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005206 CK_UserDefinedConversion, Result.get(),
5207 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005208 }
5209 return false;
5210}
5211
5212static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5213 Sema::ContextualImplicitConverter &Converter,
5214 QualType T, bool HadMultipleCandidates,
5215 DeclAccessPair &Found) {
5216 CXXConversionDecl *Conversion =
5217 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005218 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005219
5220 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5221 if (!Converter.SuppressConversion) {
5222 if (SemaRef.isSFINAEContext())
5223 return true;
5224
5225 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5226 << From->getSourceRange();
5227 }
5228
5229 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5230 HadMultipleCandidates);
5231 if (Result.isInvalid())
5232 return true;
5233 // Record usage of conversion in an implicit cast.
5234 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005235 CK_UserDefinedConversion, Result.get(),
5236 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005237 return false;
5238}
5239
5240static ExprResult finishContextualImplicitConversion(
5241 Sema &SemaRef, SourceLocation Loc, Expr *From,
5242 Sema::ContextualImplicitConverter &Converter) {
5243 if (!Converter.match(From->getType()) && !Converter.Suppress)
5244 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5245 << From->getSourceRange();
5246
5247 return SemaRef.DefaultLvalueConversion(From);
5248}
5249
5250static void
5251collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5252 UnresolvedSetImpl &ViableConversions,
5253 OverloadCandidateSet &CandidateSet) {
5254 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5255 DeclAccessPair FoundDecl = ViableConversions[I];
5256 NamedDecl *D = FoundDecl.getDecl();
5257 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5258 if (isa<UsingShadowDecl>(D))
5259 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5260
5261 CXXConversionDecl *Conv;
5262 FunctionTemplateDecl *ConvTemplate;
5263 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5264 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5265 else
5266 Conv = cast<CXXConversionDecl>(D);
5267
5268 if (ConvTemplate)
5269 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005270 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5271 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005272 else
5273 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005274 ToType, CandidateSet,
5275 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005276 }
5277}
5278
Richard Smithccc11812013-05-21 19:05:48 +00005279/// \brief Attempt to convert the given expression to a type which is accepted
5280/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005281///
Richard Smithccc11812013-05-21 19:05:48 +00005282/// This routine will attempt to convert an expression of class type to a
5283/// type accepted by the specified converter. In C++11 and before, the class
5284/// must have a single non-explicit conversion function converting to a matching
5285/// type. In C++1y, there can be multiple such conversion functions, but only
5286/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005287///
Douglas Gregor4799d032010-06-30 00:20:43 +00005288/// \param Loc The source location of the construct that requires the
5289/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005290///
James Dennett18348b62012-06-22 08:52:37 +00005291/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005292///
Richard Smithccc11812013-05-21 19:05:48 +00005293/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005294///
Douglas Gregor4799d032010-06-30 00:20:43 +00005295/// \returns The expression, converted to an integral or enumeration type if
5296/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005297ExprResult Sema::PerformContextualImplicitConversion(
5298 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005299 // We can't perform any more checking for type-dependent expressions.
5300 if (From->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005301 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005302
Eli Friedman1da70392012-01-26 00:26:18 +00005303 // Process placeholders immediately.
5304 if (From->hasPlaceholderType()) {
5305 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005306 if (result.isInvalid())
5307 return result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005308 From = result.get();
Eli Friedman1da70392012-01-26 00:26:18 +00005309 }
5310
Richard Smithccc11812013-05-21 19:05:48 +00005311 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005312 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005313 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005314 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005315
5316 // FIXME: Check for missing '()' if T is a function type?
5317
Richard Smithccc11812013-05-21 19:05:48 +00005318 // We can only perform contextual implicit conversions on objects of class
5319 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005320 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005321 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005322 if (!Converter.Suppress)
5323 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005324 return From;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005325 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005326
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005327 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005328 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005329 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005330 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005331
5332 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5333 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5334
Craig Toppere14c0f82014-03-12 04:55:44 +00005335 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00005336 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005337 }
Richard Smithccc11812013-05-21 19:05:48 +00005338 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005339
5340 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005341 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005342
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005343 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005344 UnresolvedSet<4>
5345 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005346 UnresolvedSet<4> ExplicitConversions;
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00005347 std::pair<CXXRecordDecl::conversion_iterator,
Larisse Voufo236bec22013-06-10 06:50:24 +00005348 CXXRecordDecl::conversion_iterator> Conversions =
5349 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005350
Larisse Voufo236bec22013-06-10 06:50:24 +00005351 bool HadMultipleCandidates =
5352 (std::distance(Conversions.first, Conversions.second) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005353
Larisse Voufo236bec22013-06-10 06:50:24 +00005354 // To check that there is only one target type, in C++1y:
5355 QualType ToType;
5356 bool HasUniqueTargetType = true;
5357
5358 // Collect explicit or viable (potentially in C++1y) conversions.
5359 for (CXXRecordDecl::conversion_iterator I = Conversions.first,
5360 E = Conversions.second;
5361 I != E; ++I) {
5362 NamedDecl *D = (*I)->getUnderlyingDecl();
5363 CXXConversionDecl *Conversion;
5364 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5365 if (ConvTemplate) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005366 if (getLangOpts().CPlusPlus14)
Larisse Voufo236bec22013-06-10 06:50:24 +00005367 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5368 else
5369 continue; // C++11 does not consider conversion operator templates(?).
5370 } else
5371 Conversion = cast<CXXConversionDecl>(D);
5372
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005373 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
Larisse Voufo236bec22013-06-10 06:50:24 +00005374 "Conversion operator templates are considered potentially "
5375 "viable in C++1y");
5376
5377 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5378 if (Converter.match(CurToType) || ConvTemplate) {
5379
5380 if (Conversion->isExplicit()) {
5381 // FIXME: For C++1y, do we need this restriction?
5382 // cf. diagnoseNoViableConversion()
5383 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005384 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005385 } else {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005386 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005387 if (ToType.isNull())
5388 ToType = CurToType.getUnqualifiedType();
5389 else if (HasUniqueTargetType &&
5390 (CurToType.getUnqualifiedType() != ToType))
5391 HasUniqueTargetType = false;
5392 }
5393 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005394 }
Richard Smith8dd34252012-02-04 07:07:42 +00005395 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005396 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005397
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005398 if (getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005399 // C++1y [conv]p6:
5400 // ... An expression e of class type E appearing in such a context
5401 // is said to be contextually implicitly converted to a specified
5402 // type T and is well-formed if and only if e can be implicitly
5403 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005404 // for conversion functions whose return type is cv T or reference to
5405 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005406 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005407
Larisse Voufo236bec22013-06-10 06:50:24 +00005408 // If no unique T is found:
5409 if (ToType.isNull()) {
5410 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5411 HadMultipleCandidates,
5412 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005413 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005414 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005415 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005416
Larisse Voufo236bec22013-06-10 06:50:24 +00005417 // If more than one unique Ts are found:
5418 if (!HasUniqueTargetType)
5419 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5420 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005421
Larisse Voufo236bec22013-06-10 06:50:24 +00005422 // If one unique T is found:
5423 // First, build a candidate set from the previously recorded
5424 // potentially viable conversions.
Richard Smith100b24a2014-04-17 01:52:14 +00005425 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo236bec22013-06-10 06:50:24 +00005426 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5427 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005428
Larisse Voufo236bec22013-06-10 06:50:24 +00005429 // Then, perform overload resolution over the candidate set.
5430 OverloadCandidateSet::iterator Best;
5431 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5432 case OR_Success: {
5433 // Apply this conversion.
5434 DeclAccessPair Found =
5435 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5436 if (recordConversion(*this, Loc, From, Converter, T,
5437 HadMultipleCandidates, Found))
5438 return ExprError();
5439 break;
5440 }
5441 case OR_Ambiguous:
5442 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5443 ViableConversions);
5444 case OR_No_Viable_Function:
5445 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5446 HadMultipleCandidates,
5447 ExplicitConversions))
5448 return ExprError();
5449 // fall through 'OR_Deleted' case.
5450 case OR_Deleted:
5451 // We'll complain below about a non-integral condition type.
5452 break;
5453 }
5454 } else {
5455 switch (ViableConversions.size()) {
5456 case 0: {
5457 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5458 HadMultipleCandidates,
5459 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005460 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005461
Larisse Voufo236bec22013-06-10 06:50:24 +00005462 // We'll complain below about a non-integral condition type.
5463 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005464 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005465 case 1: {
5466 // Apply this conversion.
5467 DeclAccessPair Found = ViableConversions[0];
5468 if (recordConversion(*this, Loc, From, Converter, T,
5469 HadMultipleCandidates, Found))
5470 return ExprError();
5471 break;
5472 }
5473 default:
5474 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5475 ViableConversions);
5476 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005477 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005478
Larisse Voufo236bec22013-06-10 06:50:24 +00005479 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005480}
5481
Richard Smith100b24a2014-04-17 01:52:14 +00005482/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5483/// an acceptable non-member overloaded operator for a call whose
5484/// arguments have types T1 (and, if non-empty, T2). This routine
5485/// implements the check in C++ [over.match.oper]p3b2 concerning
5486/// enumeration types.
5487static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5488 FunctionDecl *Fn,
5489 ArrayRef<Expr *> Args) {
5490 QualType T1 = Args[0]->getType();
5491 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5492
5493 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5494 return true;
5495
5496 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5497 return true;
5498
5499 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5500 if (Proto->getNumParams() < 1)
5501 return false;
5502
5503 if (T1->isEnumeralType()) {
5504 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5505 if (Context.hasSameUnqualifiedType(T1, ArgType))
5506 return true;
5507 }
5508
5509 if (Proto->getNumParams() < 2)
5510 return false;
5511
5512 if (!T2.isNull() && T2->isEnumeralType()) {
5513 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5514 if (Context.hasSameUnqualifiedType(T2, ArgType))
5515 return true;
5516 }
5517
5518 return false;
5519}
5520
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005521/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005522/// candidate functions, using the given function call arguments. If
5523/// @p SuppressUserConversions, then don't allow user-defined
5524/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005525///
James Dennett2a4d13c2012-06-15 07:13:21 +00005526/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005527/// based on an incomplete set of function arguments. This feature is used by
5528/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005529void
5530Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005531 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005532 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005533 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005534 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005535 bool PartialOverloading,
5536 bool AllowExplicit) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005537 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005538 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005539 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005540 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005541 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005542
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005543 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005544 if (!isa<CXXConstructorDecl>(Method)) {
5545 // If we get here, it's because we're calling a member function
5546 // that is named without a member access expression (e.g.,
5547 // "this->f") that was either written explicitly or created
5548 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005549 // function, e.g., X::f(). We use an empty type for the implied
5550 // object argument (C++ [over.call.func]p3), and the acting context
5551 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005552 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005553 QualType(), Expr::Classification::makeSimpleLValue(),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005554 Args, CandidateSet, SuppressUserConversions,
5555 PartialOverloading);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005556 return;
5557 }
5558 // We treat a constructor like a non-member function, since its object
5559 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005560 }
5561
Douglas Gregorff7028a2009-11-13 23:59:09 +00005562 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005563 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005564
Richard Smith100b24a2014-04-17 01:52:14 +00005565 // C++ [over.match.oper]p3:
5566 // if no operand has a class type, only those non-member functions in the
5567 // lookup set that have a first parameter of type T1 or "reference to
5568 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5569 // is a right operand) a second parameter of type T2 or "reference to
5570 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5571 // candidate functions.
5572 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5573 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5574 return;
5575
Richard Smith8b86f2d2013-11-04 01:48:18 +00005576 // C++11 [class.copy]p11: [DR1402]
5577 // A defaulted move constructor that is defined as deleted is ignored by
5578 // overload resolution.
5579 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5580 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5581 Constructor->isMoveConstructor())
5582 return;
5583
Douglas Gregor27381f32009-11-23 12:27:39 +00005584 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005585 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005586
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005587 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005588 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005589 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005590 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005591 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005592 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005593 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005594 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005595
John McCall578a1f82014-12-14 01:46:53 +00005596 if (Constructor) {
5597 // C++ [class.copy]p3:
5598 // A member function template is never instantiated to perform the copy
5599 // of a class object to an object of its class type.
5600 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5601 if (Args.size() == 1 &&
5602 Constructor->isSpecializationCopyingObject() &&
5603 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5604 IsDerivedFrom(Args[0]->getType(), ClassType))) {
5605 Candidate.Viable = false;
5606 Candidate.FailureKind = ovl_fail_illegal_constructor;
5607 return;
5608 }
5609 }
5610
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005611 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005612
5613 // (C++ 13.3.2p2): A candidate function having fewer than m
5614 // parameters is viable only if it has an ellipsis in its parameter
5615 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005616 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005617 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005618 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005619 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005620 return;
5621 }
5622
5623 // (C++ 13.3.2p2): A candidate function having more than m parameters
5624 // is viable only if the (m+1)st parameter has a default argument
5625 // (8.3.6). For the purposes of overload resolution, the
5626 // parameter list is truncated on the right, so that there are
5627 // exactly m parameters.
5628 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005629 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005630 // Not enough arguments.
5631 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005632 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005633 return;
5634 }
5635
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005636 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005637 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005638 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005639 // Skip the check for callers that are implicit members, because in this
5640 // case we may not yet know what the member's target is; the target is
5641 // inferred for the member automatically, based on the bases and fields of
5642 // the class.
5643 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005644 Candidate.Viable = false;
5645 Candidate.FailureKind = ovl_fail_bad_target;
5646 return;
5647 }
5648
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005649 // Determine the implicit conversion sequences for each of the
5650 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005651 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005652 if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005653 // (C++ 13.3.2p3): for F to be a viable function, there shall
5654 // exist for each argument an implicit conversion sequence
5655 // (13.3.3.1) that converts that argument to the corresponding
5656 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005657 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005658 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005659 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005660 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005661 /*InOverloadResolution=*/true,
5662 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005663 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005664 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005665 if (Candidate.Conversions[ArgIdx].isBad()) {
5666 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005667 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005668 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005669 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005670 } else {
5671 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5672 // argument for which there is no corresponding parameter is
5673 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005674 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005675 }
5676 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005677
5678 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5679 Candidate.Viable = false;
5680 Candidate.FailureKind = ovl_fail_enable_if;
5681 Candidate.DeductionFailure.Data = FailedAttr;
5682 return;
5683 }
5684}
5685
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005686ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args,
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00005687 bool IsInstance) {
5688 SmallVector<ObjCMethodDecl*, 4> Methods;
5689 if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance))
5690 return nullptr;
5691
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005692 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5693 bool Match = true;
5694 ObjCMethodDecl *Method = Methods[b];
5695 unsigned NumNamedArgs = Sel.getNumArgs();
5696 // Method might have more arguments than selector indicates. This is due
5697 // to addition of c-style arguments in method.
5698 if (Method->param_size() > NumNamedArgs)
5699 NumNamedArgs = Method->param_size();
5700 if (Args.size() < NumNamedArgs)
5701 continue;
5702
5703 for (unsigned i = 0; i < NumNamedArgs; i++) {
5704 // We can't do any type-checking on a type-dependent argument.
5705 if (Args[i]->isTypeDependent()) {
5706 Match = false;
5707 break;
5708 }
5709
5710 ParmVarDecl *param = Method->parameters()[i];
5711 Expr *argExpr = Args[i];
5712 assert(argExpr && "SelectBestMethod(): missing expression");
5713
5714 // Strip the unbridged-cast placeholder expression off unless it's
5715 // a consumed argument.
5716 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5717 !param->hasAttr<CFConsumedAttr>())
5718 argExpr = stripARCUnbridgedCast(argExpr);
5719
5720 // If the parameter is __unknown_anytype, move on to the next method.
5721 if (param->getType() == Context.UnknownAnyTy) {
5722 Match = false;
5723 break;
5724 }
5725
5726 ImplicitConversionSequence ConversionState
5727 = TryCopyInitialization(*this, argExpr, param->getType(),
5728 /*SuppressUserConversions*/false,
5729 /*InOverloadResolution=*/true,
5730 /*AllowObjCWritebackConversion=*/
5731 getLangOpts().ObjCAutoRefCount,
5732 /*AllowExplicit*/false);
5733 if (ConversionState.isBad()) {
5734 Match = false;
5735 break;
5736 }
5737 }
5738 // Promote additional arguments to variadic methods.
5739 if (Match && Method->isVariadic()) {
5740 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
5741 if (Args[i]->isTypeDependent()) {
5742 Match = false;
5743 break;
5744 }
5745 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
5746 nullptr);
5747 if (Arg.isInvalid()) {
5748 Match = false;
5749 break;
5750 }
5751 }
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005752 } else {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005753 // Check for extra arguments to non-variadic methods.
5754 if (Args.size() != NumNamedArgs)
5755 Match = false;
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005756 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
5757 // Special case when selectors have no argument. In this case, select
5758 // one with the most general result type of 'id'.
5759 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5760 QualType ReturnT = Methods[b]->getReturnType();
5761 if (ReturnT->isObjCIdType())
5762 return Methods[b];
5763 }
5764 }
5765 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005766
5767 if (Match)
5768 return Method;
5769 }
5770 return nullptr;
5771}
5772
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005773static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); }
5774
5775EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5776 bool MissingImplicitThis) {
5777 // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but
5778 // we need to find the first failing one.
5779 if (!Function->hasAttrs())
Craig Topperc3ec1492014-05-26 06:22:03 +00005780 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005781 AttrVec Attrs = Function->getAttrs();
5782 AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(),
5783 IsNotEnableIfAttr);
5784 if (Attrs.begin() == E)
Craig Topperc3ec1492014-05-26 06:22:03 +00005785 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005786 std::reverse(Attrs.begin(), E);
5787
5788 SFINAETrap Trap(*this);
5789
5790 // Convert the arguments.
5791 SmallVector<Expr *, 16> ConvertedArgs;
5792 bool InitializationFailed = false;
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005793 bool ContainsValueDependentExpr = false;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005794 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5795 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
Nick Lewyckyb8336b72014-02-28 05:26:13 +00005796 !cast<CXXMethodDecl>(Function)->isStatic() &&
5797 !isa<CXXConstructorDecl>(Function)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005798 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5799 ExprResult R =
Craig Topperc3ec1492014-05-26 06:22:03 +00005800 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005801 Method, Method);
5802 if (R.isInvalid()) {
5803 InitializationFailed = true;
5804 break;
5805 }
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005806 ContainsValueDependentExpr |= R.get()->isValueDependent();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005807 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005808 } else {
5809 ExprResult R =
5810 PerformCopyInitialization(InitializedEntity::InitializeParameter(
5811 Context,
5812 Function->getParamDecl(i)),
5813 SourceLocation(),
5814 Args[i]);
5815 if (R.isInvalid()) {
5816 InitializationFailed = true;
5817 break;
5818 }
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005819 ContainsValueDependentExpr |= R.get()->isValueDependent();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005820 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005821 }
5822 }
5823
5824 if (InitializationFailed || Trap.hasErrorOccurred())
5825 return cast<EnableIfAttr>(Attrs[0]);
5826
5827 for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) {
5828 APValue Result;
5829 EnableIfAttr *EIA = cast<EnableIfAttr>(*I);
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005830 if (EIA->getCond()->isValueDependent()) {
5831 // Don't even try now, we'll examine it after instantiation.
5832 continue;
5833 }
5834
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005835 if (!EIA->getCond()->EvaluateWithSubstitution(
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005836 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) {
5837 if (!ContainsValueDependentExpr)
5838 return EIA;
5839 } else if (!Result.isInt() || !Result.getInt().getBoolValue()) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005840 return EIA;
5841 }
5842 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005843 return nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005844}
5845
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005846/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00005847/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00005848void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005849 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005850 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005851 TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smithbcc22fc2012-03-09 08:00:36 +00005852 bool SuppressUserConversions,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005853 bool PartialOverloading) {
John McCall4c4c1df2010-01-26 03:27:55 +00005854 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00005855 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5856 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005857 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005858 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005859 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00005860 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005861 Args.slice(1), CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005862 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005863 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005864 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005865 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005866 } else {
John McCalla0296f72010-03-19 07:35:19 +00005867 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005868 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5869 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005870 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005871 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005872 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005873 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005874 Args[0]->Classify(Context), Args.slice(1),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005875 CandidateSet, SuppressUserConversions,
5876 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005877 else
John McCalla0296f72010-03-19 07:35:19 +00005878 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005879 ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005880 CandidateSet, SuppressUserConversions,
5881 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005882 }
Douglas Gregor15448f82009-06-27 21:05:07 +00005883 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005884}
5885
John McCallf0f1cf02009-11-17 07:50:12 +00005886/// AddMethodCandidate - Adds a named decl (which is some kind of
5887/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00005888void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005889 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005890 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005891 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00005892 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005893 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00005894 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00005895 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00005896
5897 if (isa<UsingShadowDecl>(Decl))
5898 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005899
John McCallf0f1cf02009-11-17 07:50:12 +00005900 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5901 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5902 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00005903 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
Craig Topperc3ec1492014-05-26 06:22:03 +00005904 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005905 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005906 Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005907 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005908 } else {
John McCalla0296f72010-03-19 07:35:19 +00005909 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005910 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005911 Args,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005912 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005913 }
5914}
5915
Douglas Gregor436424c2008-11-18 23:14:02 +00005916/// AddMethodCandidate - Adds the given C++ member function to the set
5917/// of candidate functions, using the given function call arguments
5918/// and the object argument (@c Object). For example, in a call
5919/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5920/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5921/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00005922/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00005923void
John McCalla0296f72010-03-19 07:35:19 +00005924Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00005925 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005926 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005927 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005928 OverloadCandidateSet &CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005929 bool SuppressUserConversions,
5930 bool PartialOverloading) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005931 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005932 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00005933 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005934 assert(!isa<CXXConstructorDecl>(Method) &&
5935 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00005936
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005937 if (!CandidateSet.isNewCandidate(Method))
5938 return;
5939
Richard Smith8b86f2d2013-11-04 01:48:18 +00005940 // C++11 [class.copy]p23: [DR1402]
5941 // A defaulted move assignment operator that is defined as deleted is
5942 // ignored by overload resolution.
5943 if (Method->isDefaulted() && Method->isDeleted() &&
5944 Method->isMoveAssignmentOperator())
5945 return;
5946
Douglas Gregor27381f32009-11-23 12:27:39 +00005947 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005948 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005949
Douglas Gregor436424c2008-11-18 23:14:02 +00005950 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005951 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00005952 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00005953 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005954 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005955 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005956 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00005957
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005958 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00005959
5960 // (C++ 13.3.2p2): A candidate function having fewer than m
5961 // parameters is viable only if it has an ellipsis in its parameter
5962 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005963 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
5964 !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005965 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005966 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005967 return;
5968 }
5969
5970 // (C++ 13.3.2p2): A candidate function having more than m parameters
5971 // is viable only if the (m+1)st parameter has a default argument
5972 // (8.3.6). For the purposes of overload resolution, the
5973 // parameter list is truncated on the right, so that there are
5974 // exactly m parameters.
5975 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005976 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005977 // Not enough arguments.
5978 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005979 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005980 return;
5981 }
5982
5983 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00005984
John McCall6e9f8f62009-12-03 04:06:58 +00005985 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005986 // The implicit object argument is ignored.
5987 Candidate.IgnoreObjectArgument = true;
5988 else {
5989 // Determine the implicit conversion sequence for the object
5990 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00005991 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00005992 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5993 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005994 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005995 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005996 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005997 return;
5998 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005999 }
6000
Eli Bendersky291a57e2014-09-25 23:59:08 +00006001 // (CUDA B.1): Check for invalid calls between targets.
6002 if (getLangOpts().CUDA)
6003 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6004 if (CheckCUDATarget(Caller, Method)) {
6005 Candidate.Viable = false;
6006 Candidate.FailureKind = ovl_fail_bad_target;
6007 return;
6008 }
6009
Douglas Gregor436424c2008-11-18 23:14:02 +00006010 // Determine the implicit conversion sequences for each of the
6011 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006012 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006013 if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006014 // (C++ 13.3.2p3): for F to be a viable function, there shall
6015 // exist for each argument an implicit conversion sequence
6016 // (13.3.3.1) that converts that argument to the corresponding
6017 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006018 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006019 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006020 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006021 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006022 /*InOverloadResolution=*/true,
6023 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006024 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006025 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006026 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006027 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006028 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006029 }
6030 } else {
6031 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6032 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006033 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006034 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00006035 }
6036 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006037
6038 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6039 Candidate.Viable = false;
6040 Candidate.FailureKind = ovl_fail_enable_if;
6041 Candidate.DeductionFailure.Data = FailedAttr;
6042 return;
6043 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006044}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006045
Douglas Gregor97628d62009-08-21 00:16:32 +00006046/// \brief Add a C++ member function template as a candidate to the candidate
6047/// set, using template argument deduction to produce an appropriate member
6048/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006049void
Douglas Gregor97628d62009-08-21 00:16:32 +00006050Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00006051 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006052 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006053 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006054 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006055 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006056 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00006057 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006058 bool SuppressUserConversions,
6059 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006060 if (!CandidateSet.isNewCandidate(MethodTmpl))
6061 return;
6062
Douglas Gregor97628d62009-08-21 00:16:32 +00006063 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006064 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006065 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006066 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00006067 // candidate functions in the usual way.113) A given name can refer to one
6068 // or more function templates and also to a set of overloaded non-template
6069 // functions. In such a case, the candidate functions generated from each
6070 // function template are combined with the set of non-template candidate
6071 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006072 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006073 FunctionDecl *Specialization = nullptr;
Douglas Gregor97628d62009-08-21 00:16:32 +00006074 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006075 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006076 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006077 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006078 Candidate.FoundDecl = FoundDecl;
6079 Candidate.Function = MethodTmpl->getTemplatedDecl();
6080 Candidate.Viable = false;
6081 Candidate.FailureKind = ovl_fail_bad_deduction;
6082 Candidate.IsSurrogate = false;
6083 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006084 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006085 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006086 Info);
6087 return;
6088 }
Mike Stump11289f42009-09-09 15:08:12 +00006089
Douglas Gregor97628d62009-08-21 00:16:32 +00006090 // Add the function template specialization produced by template argument
6091 // deduction as a candidate.
6092 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00006093 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00006094 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00006095 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006096 ActingContext, ObjectType, ObjectClassification, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006097 CandidateSet, SuppressUserConversions, PartialOverloading);
Douglas Gregor97628d62009-08-21 00:16:32 +00006098}
6099
Douglas Gregor05155d82009-08-21 23:19:43 +00006100/// \brief Add a C++ function template specialization as a candidate
6101/// in the candidate set, using template argument deduction to produce
6102/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006103void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006104Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006105 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006106 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006107 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006108 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006109 bool SuppressUserConversions,
6110 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006111 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6112 return;
6113
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006114 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006115 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006116 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006117 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006118 // candidate functions in the usual way.113) A given name can refer to one
6119 // or more function templates and also to a set of overloaded non-template
6120 // functions. In such a case, the candidate functions generated from each
6121 // function template are combined with the set of non-template candidate
6122 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006123 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006124 FunctionDecl *Specialization = nullptr;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006125 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006126 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006127 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006128 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00006129 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00006130 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6131 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006132 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00006133 Candidate.IsSurrogate = false;
6134 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006135 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006136 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006137 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006138 return;
6139 }
Mike Stump11289f42009-09-09 15:08:12 +00006140
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006141 // Add the function template specialization produced by template argument
6142 // deduction as a candidate.
6143 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006144 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006145 SuppressUserConversions, PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006146}
Mike Stump11289f42009-09-09 15:08:12 +00006147
Douglas Gregor4b60a152013-11-07 22:34:54 +00006148/// Determine whether this is an allowable conversion from the result
6149/// of an explicit conversion operator to the expected type, per C++
6150/// [over.match.conv]p1 and [over.match.ref]p1.
6151///
6152/// \param ConvType The return type of the conversion function.
6153///
6154/// \param ToType The type we are converting to.
6155///
6156/// \param AllowObjCPointerConversion Allow a conversion from one
6157/// Objective-C pointer to another.
6158///
6159/// \returns true if the conversion is allowable, false otherwise.
6160static bool isAllowableExplicitConversion(Sema &S,
6161 QualType ConvType, QualType ToType,
6162 bool AllowObjCPointerConversion) {
6163 QualType ToNonRefType = ToType.getNonReferenceType();
6164
6165 // Easy case: the types are the same.
6166 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6167 return true;
6168
6169 // Allow qualification conversions.
6170 bool ObjCLifetimeConversion;
6171 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6172 ObjCLifetimeConversion))
6173 return true;
6174
6175 // If we're not allowed to consider Objective-C pointer conversions,
6176 // we're done.
6177 if (!AllowObjCPointerConversion)
6178 return false;
6179
6180 // Is this an Objective-C pointer conversion?
6181 bool IncompatibleObjC = false;
6182 QualType ConvertedType;
6183 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6184 IncompatibleObjC);
6185}
6186
Douglas Gregora1f013e2008-11-07 22:36:19 +00006187/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006188/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006189/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006190/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006191/// (which may or may not be the same type as the type that the
6192/// conversion function produces).
6193void
6194Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006195 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006196 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006197 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006198 OverloadCandidateSet& CandidateSet,
6199 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006200 assert(!Conversion->getDescribedFunctionTemplate() &&
6201 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006202 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006203 if (!CandidateSet.isNewCandidate(Conversion))
6204 return;
6205
Richard Smith2a7d4812013-05-04 07:00:32 +00006206 // If the conversion function has an undeduced return type, trigger its
6207 // deduction now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006208 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00006209 if (DeduceReturnType(Conversion, From->getExprLoc()))
6210 return;
6211 ConvType = Conversion->getConversionType().getNonReferenceType();
6212 }
6213
Richard Smith089c3162013-09-21 21:55:46 +00006214 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6215 // operator is only a candidate if its return type is the target type or
6216 // can be converted to the target type with a qualification conversion.
Douglas Gregor4b60a152013-11-07 22:34:54 +00006217 if (Conversion->isExplicit() &&
6218 !isAllowableExplicitConversion(*this, ConvType, ToType,
6219 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006220 return;
6221
Douglas Gregor27381f32009-11-23 12:27:39 +00006222 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006223 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006224
Douglas Gregora1f013e2008-11-07 22:36:19 +00006225 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006226 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006227 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006228 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006229 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006230 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006231 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006232 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006233 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006234 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006235 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006236
Douglas Gregor6affc782010-08-19 15:37:02 +00006237 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006238 // For conversion functions, the function is considered to be a member of
6239 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006240 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006241 //
6242 // Determine the implicit conversion sequence for the implicit
6243 // object parameter.
6244 QualType ImplicitParamType = From->getType();
6245 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6246 ImplicitParamType = FromPtrType->getPointeeType();
6247 CXXRecordDecl *ConversionContext
6248 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006249
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006250 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006251 = TryObjectArgumentInitialization(*this, From->getType(),
6252 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00006253 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006254
John McCall0d1da222010-01-12 00:44:57 +00006255 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006256 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006257 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006258 return;
6259 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006260
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006261 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006262 // derived to base as such conversions are given Conversion Rank. They only
6263 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6264 QualType FromCanon
6265 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6266 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6267 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
6268 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006269 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006270 return;
6271 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006272
Douglas Gregora1f013e2008-11-07 22:36:19 +00006273 // To determine what the conversion from the result of calling the
6274 // conversion function to the type we're eventually trying to
6275 // convert to (ToType), we need to synthesize a call to the
6276 // conversion function and attempt copy initialization from it. This
6277 // makes sure that we get the right semantics with respect to
6278 // lvalues/rvalues and the type. Fortunately, we can allocate this
6279 // call on the stack and we don't need its arguments to be
6280 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006281 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006282 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006283 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6284 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006285 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006286 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006287
Richard Smith48d24642011-07-13 22:53:21 +00006288 QualType ConversionType = Conversion->getConversionType();
6289 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006290 Candidate.Viable = false;
6291 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6292 return;
6293 }
6294
Richard Smith48d24642011-07-13 22:53:21 +00006295 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006296
Mike Stump11289f42009-09-09 15:08:12 +00006297 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006298 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6299 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006300 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006301 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006302 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006303 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006304 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006305 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006306 /*InOverloadResolution=*/false,
6307 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006308
John McCall0d1da222010-01-12 00:44:57 +00006309 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006310 case ImplicitConversionSequence::StandardConversion:
6311 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006312
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006313 // C++ [over.ics.user]p3:
6314 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006315 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006316 // shall have exact match rank.
6317 if (Conversion->getPrimaryTemplate() &&
6318 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6319 Candidate.Viable = false;
6320 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006321 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006322 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006323
Douglas Gregorcba72b12011-01-21 05:18:22 +00006324 // C++0x [dcl.init.ref]p5:
6325 // In the second case, if the reference is an rvalue reference and
6326 // the second standard conversion sequence of the user-defined
6327 // conversion sequence includes an lvalue-to-rvalue conversion, the
6328 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006329 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006330 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6331 Candidate.Viable = false;
6332 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006333 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006334 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006335 break;
6336
6337 case ImplicitConversionSequence::BadConversion:
6338 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006339 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006340 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006341
6342 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006343 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006344 "Can only end up with a standard conversion sequence or failure");
6345 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006346
Craig Topper5fc8fc22014-08-27 06:28:36 +00006347 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006348 Candidate.Viable = false;
6349 Candidate.FailureKind = ovl_fail_enable_if;
6350 Candidate.DeductionFailure.Data = FailedAttr;
6351 return;
6352 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006353}
6354
Douglas Gregor05155d82009-08-21 23:19:43 +00006355/// \brief Adds a conversion function template specialization
6356/// candidate to the overload set, using template argument deduction
6357/// to deduce the template arguments of the conversion function
6358/// template from the type that we are converting to (C++
6359/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006360void
Douglas Gregor05155d82009-08-21 23:19:43 +00006361Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006362 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006363 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00006364 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006365 OverloadCandidateSet &CandidateSet,
6366 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006367 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6368 "Only conversion function templates permitted here");
6369
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006370 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6371 return;
6372
Craig Toppere6706e42012-09-19 02:26:47 +00006373 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006374 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00006375 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006376 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006377 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006378 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006379 Candidate.FoundDecl = FoundDecl;
6380 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6381 Candidate.Viable = false;
6382 Candidate.FailureKind = ovl_fail_bad_deduction;
6383 Candidate.IsSurrogate = false;
6384 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006385 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006386 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006387 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006388 return;
6389 }
Mike Stump11289f42009-09-09 15:08:12 +00006390
Douglas Gregor05155d82009-08-21 23:19:43 +00006391 // Add the conversion function template specialization produced by
6392 // template argument deduction as a candidate.
6393 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00006394 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006395 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor05155d82009-08-21 23:19:43 +00006396}
6397
Douglas Gregorab7897a2008-11-19 22:57:39 +00006398/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6399/// converts the given @c Object to a function pointer via the
6400/// conversion function @c Conversion, and then attempts to call it
6401/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6402/// the type of function that we'll eventually be calling.
6403void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006404 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006405 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006406 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00006407 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006408 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00006409 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006410 if (!CandidateSet.isNewCandidate(Conversion))
6411 return;
6412
Douglas Gregor27381f32009-11-23 12:27:39 +00006413 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006414 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006415
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006416 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006417 Candidate.FoundDecl = FoundDecl;
Craig Topperc3ec1492014-05-26 06:22:03 +00006418 Candidate.Function = nullptr;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006419 Candidate.Surrogate = Conversion;
6420 Candidate.Viable = true;
6421 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006422 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006423 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006424
6425 // Determine the implicit conversion sequence for the implicit
6426 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00006427 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006428 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00006429 Object->Classify(Context),
6430 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006431 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006432 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006433 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00006434 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006435 return;
6436 }
6437
6438 // The first conversion is actually a user-defined conversion whose
6439 // first conversion is ObjectInit's standard conversion (which is
6440 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00006441 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006442 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00006443 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006444 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006445 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00006446 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00006447 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00006448 = Candidate.Conversions[0].UserDefined.Before;
6449 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6450
Mike Stump11289f42009-09-09 15:08:12 +00006451 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006452 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006453
6454 // (C++ 13.3.2p2): A candidate function having fewer than m
6455 // parameters is viable only if it has an ellipsis in its parameter
6456 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006457 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006458 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006459 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006460 return;
6461 }
6462
6463 // Function types don't have any default arguments, so just check if
6464 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006465 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006466 // Not enough arguments.
6467 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006468 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006469 return;
6470 }
6471
6472 // Determine the implicit conversion sequences for each of the
6473 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00006474 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006475 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006476 // (C++ 13.3.2p3): for F to be a viable function, there shall
6477 // exist for each argument an implicit conversion sequence
6478 // (13.3.3.1) that converts that argument to the corresponding
6479 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006480 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006481 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006482 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006483 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00006484 /*InOverloadResolution=*/false,
6485 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006486 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006487 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006488 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006489 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006490 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006491 }
6492 } else {
6493 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6494 // argument for which there is no corresponding parameter is
6495 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006496 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006497 }
6498 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006499
Craig Topper5fc8fc22014-08-27 06:28:36 +00006500 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006501 Candidate.Viable = false;
6502 Candidate.FailureKind = ovl_fail_enable_if;
6503 Candidate.DeductionFailure.Data = FailedAttr;
6504 return;
6505 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00006506}
6507
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006508/// \brief Add overload candidates for overloaded operators that are
6509/// member functions.
6510///
6511/// Add the overloaded operator candidates that are member functions
6512/// for the operator Op that was used in an operator expression such
6513/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6514/// CandidateSet will store the added overload candidates. (C++
6515/// [over.match.oper]).
6516void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6517 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00006518 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006519 OverloadCandidateSet& CandidateSet,
6520 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006521 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6522
6523 // C++ [over.match.oper]p3:
6524 // For a unary operator @ with an operand of a type whose
6525 // cv-unqualified version is T1, and for a binary operator @ with
6526 // a left operand of a type whose cv-unqualified version is T1 and
6527 // a right operand of a type whose cv-unqualified version is T2,
6528 // three sets of candidate functions, designated member
6529 // candidates, non-member candidates and built-in candidates, are
6530 // constructed as follows:
6531 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00006532
Richard Smith0feaf0c2013-04-20 12:41:22 +00006533 // -- If T1 is a complete class type or a class currently being
6534 // defined, the set of member candidates is the result of the
6535 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6536 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006537 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00006538 // Complete the type if it can be completed.
6539 RequireCompleteType(OpLoc, T1, 0);
6540 // If the type is neither complete nor being defined, bail out now.
6541 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006542 return;
Mike Stump11289f42009-09-09 15:08:12 +00006543
John McCall27b18f82009-11-17 02:14:36 +00006544 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6545 LookupQualifiedName(Operators, T1Rec->getDecl());
6546 Operators.suppressDiagnostics();
6547
Mike Stump11289f42009-09-09 15:08:12 +00006548 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006549 OperEnd = Operators.end();
6550 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00006551 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00006552 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola51629df2013-04-29 19:29:25 +00006553 Args[0]->Classify(Context),
Richard Smithe54c3072013-05-05 15:51:06 +00006554 Args.slice(1),
Douglas Gregor02824322011-01-26 19:30:28 +00006555 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006556 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00006557 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006558}
6559
Douglas Gregora11693b2008-11-12 17:17:38 +00006560/// AddBuiltinCandidate - Add a candidate for a built-in
6561/// operator. ResultTy and ParamTys are the result and parameter types
6562/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00006563/// arguments being passed to the candidate. IsAssignmentOperator
6564/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00006565/// operator. NumContextualBoolArguments is the number of arguments
6566/// (at the beginning of the argument list) that will be contextually
6567/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00006568void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smithe54c3072013-05-05 15:51:06 +00006569 ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00006570 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006571 bool IsAssignmentOperator,
6572 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00006573 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006574 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006575
Douglas Gregora11693b2008-11-12 17:17:38 +00006576 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00006577 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Craig Topperc3ec1492014-05-26 06:22:03 +00006578 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6579 Candidate.Function = nullptr;
Douglas Gregor1d248c52008-12-12 02:00:36 +00006580 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006581 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00006582 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smithe54c3072013-05-05 15:51:06 +00006583 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregora11693b2008-11-12 17:17:38 +00006584 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6585
6586 // Determine the implicit conversion sequences for each of the
6587 // arguments.
6588 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00006589 Candidate.ExplicitCallArguments = Args.size();
6590 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00006591 // C++ [over.match.oper]p4:
6592 // For the built-in assignment operators, conversions of the
6593 // left operand are restricted as follows:
6594 // -- no temporaries are introduced to hold the left operand, and
6595 // -- no user-defined conversions are applied to the left
6596 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00006597 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00006598 //
6599 // We block these conversions by turning off user-defined
6600 // conversions, since that is the only way that initialization of
6601 // a reference to a non-class type can occur from something that
6602 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006603 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006604 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006605 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006606 Candidate.Conversions[ArgIdx]
6607 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006608 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006609 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006610 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006611 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006612 /*InOverloadResolution=*/false,
6613 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006614 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006615 }
John McCall0d1da222010-01-12 00:44:57 +00006616 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006617 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006618 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006619 break;
6620 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006621 }
6622}
6623
Craig Toppercd7b0332013-07-01 06:29:40 +00006624namespace {
6625
Douglas Gregora11693b2008-11-12 17:17:38 +00006626/// BuiltinCandidateTypeSet - A set of types that will be used for the
6627/// candidate operator functions for built-in operators (C++
6628/// [over.built]). The types are separated into pointer types and
6629/// enumeration types.
6630class BuiltinCandidateTypeSet {
6631 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006632 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006633
6634 /// PointerTypes - The set of pointer types that will be used in the
6635 /// built-in candidates.
6636 TypeSet PointerTypes;
6637
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006638 /// MemberPointerTypes - The set of member pointer types that will be
6639 /// used in the built-in candidates.
6640 TypeSet MemberPointerTypes;
6641
Douglas Gregora11693b2008-11-12 17:17:38 +00006642 /// EnumerationTypes - The set of enumeration types that will be
6643 /// used in the built-in candidates.
6644 TypeSet EnumerationTypes;
6645
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006646 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006647 /// candidates.
6648 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006649
6650 /// \brief A flag indicating non-record types are viable candidates
6651 bool HasNonRecordTypes;
6652
6653 /// \brief A flag indicating whether either arithmetic or enumeration types
6654 /// were present in the candidate set.
6655 bool HasArithmeticOrEnumeralTypes;
6656
Douglas Gregor80af3132011-05-21 23:15:46 +00006657 /// \brief A flag indicating whether the nullptr type was present in the
6658 /// candidate set.
6659 bool HasNullPtrType;
6660
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006661 /// Sema - The semantic analysis instance where we are building the
6662 /// candidate type set.
6663 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006664
Douglas Gregora11693b2008-11-12 17:17:38 +00006665 /// Context - The AST context in which we will build the type sets.
6666 ASTContext &Context;
6667
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006668 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6669 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006670 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006671
6672public:
6673 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006674 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006675
Mike Stump11289f42009-09-09 15:08:12 +00006676 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006677 : HasNonRecordTypes(false),
6678 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006679 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006680 SemaRef(SemaRef),
6681 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006682
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006683 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006684 SourceLocation Loc,
6685 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006686 bool AllowExplicitConversions,
6687 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006688
6689 /// pointer_begin - First pointer type found;
6690 iterator pointer_begin() { return PointerTypes.begin(); }
6691
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006692 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006693 iterator pointer_end() { return PointerTypes.end(); }
6694
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006695 /// member_pointer_begin - First member pointer type found;
6696 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6697
6698 /// member_pointer_end - Past the last member pointer type found;
6699 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6700
Douglas Gregora11693b2008-11-12 17:17:38 +00006701 /// enumeration_begin - First enumeration type found;
6702 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6703
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006704 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006705 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006706
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006707 iterator vector_begin() { return VectorTypes.begin(); }
6708 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006709
6710 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6711 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006712 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006713};
6714
Craig Toppercd7b0332013-07-01 06:29:40 +00006715} // end anonymous namespace
6716
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006717/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006718/// the set of pointer types along with any more-qualified variants of
6719/// that type. For example, if @p Ty is "int const *", this routine
6720/// will add "int const *", "int const volatile *", "int const
6721/// restrict *", and "int const volatile restrict *" to the set of
6722/// pointer types. Returns true if the add of @p Ty itself succeeded,
6723/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006724///
6725/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006726bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006727BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6728 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006729
Douglas Gregora11693b2008-11-12 17:17:38 +00006730 // Insert this type.
David Blaikie82e95a32014-11-19 07:49:47 +00006731 if (!PointerTypes.insert(Ty).second)
Douglas Gregora11693b2008-11-12 17:17:38 +00006732 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006733
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006734 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006735 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006736 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006737 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006738 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6739 PointeeTy = PTy->getPointeeType();
6740 buildObjCPtr = true;
6741 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006742 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00006743 }
6744
Sebastian Redl4990a632009-11-18 20:39:26 +00006745 // Don't add qualified variants of arrays. For one, they're not allowed
6746 // (the qualifier would sink to the element type), and for another, the
6747 // only overload situation where it matters is subscript or pointer +- int,
6748 // and those shouldn't have qualifier variants anyway.
6749 if (PointeeTy->isArrayType())
6750 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006751
John McCall8ccfcb52009-09-24 19:53:00 +00006752 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006753 bool hasVolatile = VisibleQuals.hasVolatile();
6754 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006755
John McCall8ccfcb52009-09-24 19:53:00 +00006756 // Iterate through all strict supersets of BaseCVR.
6757 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6758 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006759 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006760 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006761
6762 // Skip over restrict if no restrict found anywhere in the types, or if
6763 // the type cannot be restrict-qualified.
6764 if ((CVR & Qualifiers::Restrict) &&
6765 (!hasRestrict ||
6766 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6767 continue;
6768
6769 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00006770 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006771
6772 // Build qualified pointer type.
6773 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006774 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00006775 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006776 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00006777 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6778
6779 // Insert qualified pointer type.
6780 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00006781 }
6782
6783 return true;
6784}
6785
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006786/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6787/// to the set of pointer types along with any more-qualified variants of
6788/// that type. For example, if @p Ty is "int const *", this routine
6789/// will add "int const *", "int const volatile *", "int const
6790/// restrict *", and "int const volatile restrict *" to the set of
6791/// pointer types. Returns true if the add of @p Ty itself succeeded,
6792/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006793///
6794/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006795bool
6796BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6797 QualType Ty) {
6798 // Insert this type.
David Blaikie82e95a32014-11-19 07:49:47 +00006799 if (!MemberPointerTypes.insert(Ty).second)
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006800 return false;
6801
John McCall8ccfcb52009-09-24 19:53:00 +00006802 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6803 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006804
John McCall8ccfcb52009-09-24 19:53:00 +00006805 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006806 // Don't add qualified variants of arrays. For one, they're not allowed
6807 // (the qualifier would sink to the element type), and for another, the
6808 // only overload situation where it matters is subscript or pointer +- int,
6809 // and those shouldn't have qualifier variants anyway.
6810 if (PointeeTy->isArrayType())
6811 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006812 const Type *ClassTy = PointerTy->getClass();
6813
6814 // Iterate through all strict supersets of the pointee type's CVR
6815 // qualifiers.
6816 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6817 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6818 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006819
John McCall8ccfcb52009-09-24 19:53:00 +00006820 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006821 MemberPointerTypes.insert(
6822 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006823 }
6824
6825 return true;
6826}
6827
Douglas Gregora11693b2008-11-12 17:17:38 +00006828/// AddTypesConvertedFrom - Add each of the types to which the type @p
6829/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006830/// primarily interested in pointer types and enumeration types. We also
6831/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006832/// AllowUserConversions is true if we should look at the conversion
6833/// functions of a class type, and AllowExplicitConversions if we
6834/// should also include the explicit conversion functions of a class
6835/// type.
Mike Stump11289f42009-09-09 15:08:12 +00006836void
Douglas Gregor5fb53972009-01-14 15:45:31 +00006837BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006838 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006839 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006840 bool AllowExplicitConversions,
6841 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006842 // Only deal with canonical types.
6843 Ty = Context.getCanonicalType(Ty);
6844
6845 // Look through reference types; they aren't part of the type of an
6846 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006847 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00006848 Ty = RefTy->getPointeeType();
6849
John McCall33ddac02011-01-19 10:06:00 +00006850 // If we're dealing with an array type, decay to the pointer.
6851 if (Ty->isArrayType())
6852 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6853
6854 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006855 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00006856
Chandler Carruth00a38332010-12-13 01:44:01 +00006857 // Flag if we ever add a non-record type.
6858 const RecordType *TyRec = Ty->getAs<RecordType>();
6859 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6860
Chandler Carruth00a38332010-12-13 01:44:01 +00006861 // Flag if we encounter an arithmetic type.
6862 HasArithmeticOrEnumeralTypes =
6863 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6864
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006865 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6866 PointerTypes.insert(Ty);
6867 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006868 // Insert our type, and its more-qualified variants, into the set
6869 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006870 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00006871 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006872 } else if (Ty->isMemberPointerType()) {
6873 // Member pointers are far easier, since the pointee can't be converted.
6874 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6875 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00006876 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006877 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00006878 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006879 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006880 // We treat vector types as arithmetic types in many contexts as an
6881 // extension.
6882 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006883 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00006884 } else if (Ty->isNullPtrType()) {
6885 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00006886 } else if (AllowUserConversions && TyRec) {
6887 // No conversion functions in incomplete types.
6888 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6889 return;
Mike Stump11289f42009-09-09 15:08:12 +00006890
Chandler Carruth00a38332010-12-13 01:44:01 +00006891 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006892 std::pair<CXXRecordDecl::conversion_iterator,
6893 CXXRecordDecl::conversion_iterator>
6894 Conversions = ClassDecl->getVisibleConversionFunctions();
6895 for (CXXRecordDecl::conversion_iterator
6896 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006897 NamedDecl *D = I.getDecl();
6898 if (isa<UsingShadowDecl>(D))
6899 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00006900
Chandler Carruth00a38332010-12-13 01:44:01 +00006901 // Skip conversion function templates; they don't tell us anything
6902 // about which builtin types we can convert to.
6903 if (isa<FunctionTemplateDecl>(D))
6904 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006905
Chandler Carruth00a38332010-12-13 01:44:01 +00006906 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6907 if (AllowExplicitConversions || !Conv->isExplicit()) {
6908 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6909 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006910 }
6911 }
6912 }
6913}
6914
Douglas Gregor84605ae2009-08-24 13:43:27 +00006915/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6916/// the volatile- and non-volatile-qualified assignment operators for the
6917/// given type to the candidate set.
6918static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6919 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00006920 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006921 OverloadCandidateSet &CandidateSet) {
6922 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00006923
Douglas Gregor84605ae2009-08-24 13:43:27 +00006924 // T& operator=(T&, T)
6925 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6926 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00006927 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006928 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00006929
Douglas Gregor84605ae2009-08-24 13:43:27 +00006930 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6931 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00006932 ParamTypes[0]
6933 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00006934 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00006935 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00006936 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00006937 }
6938}
Mike Stump11289f42009-09-09 15:08:12 +00006939
Sebastian Redl1054fae2009-10-25 17:03:50 +00006940/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6941/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006942static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6943 Qualifiers VRQuals;
6944 const RecordType *TyRec;
6945 if (const MemberPointerType *RHSMPType =
6946 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00006947 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006948 else
6949 TyRec = ArgExpr->getType()->getAs<RecordType>();
6950 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006951 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006952 VRQuals.addVolatile();
6953 VRQuals.addRestrict();
6954 return VRQuals;
6955 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006956
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006957 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00006958 if (!ClassDecl->hasDefinition())
6959 return VRQuals;
6960
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006961 std::pair<CXXRecordDecl::conversion_iterator,
6962 CXXRecordDecl::conversion_iterator>
6963 Conversions = ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006964
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006965 for (CXXRecordDecl::conversion_iterator
6966 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00006967 NamedDecl *D = I.getDecl();
6968 if (isa<UsingShadowDecl>(D))
6969 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6970 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006971 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6972 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6973 CanTy = ResTypeRef->getPointeeType();
6974 // Need to go down the pointer/mempointer chain and add qualifiers
6975 // as see them.
6976 bool done = false;
6977 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006978 if (CanTy.isRestrictQualified())
6979 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006980 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6981 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006982 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006983 CanTy->getAs<MemberPointerType>())
6984 CanTy = ResTypeMPtr->getPointeeType();
6985 else
6986 done = true;
6987 if (CanTy.isVolatileQualified())
6988 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006989 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6990 return VRQuals;
6991 }
6992 }
6993 }
6994 return VRQuals;
6995}
John McCall52872982010-11-13 05:51:15 +00006996
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006997namespace {
John McCall52872982010-11-13 05:51:15 +00006998
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006999/// \brief Helper class to manage the addition of builtin operator overload
7000/// candidates. It provides shared state and utility methods used throughout
7001/// the process, as well as a helper method to add each group of builtin
7002/// operator overloads from the standard to a candidate set.
7003class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007004 // Common instance state available to all overload candidate addition methods.
7005 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00007006 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007007 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00007008 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007009 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007010 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007011
Chandler Carruthc6586e52010-12-12 10:35:00 +00007012 // Define some constants used to index and iterate over the arithemetic types
7013 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00007014 // The "promoted arithmetic types" are the arithmetic
7015 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00007016 static const unsigned FirstIntegralType = 3;
Richard Smith521ecc12012-06-10 08:00:26 +00007017 static const unsigned LastIntegralType = 20;
John McCall52872982010-11-13 05:51:15 +00007018 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith521ecc12012-06-10 08:00:26 +00007019 LastPromotedIntegralType = 11;
John McCall52872982010-11-13 05:51:15 +00007020 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith521ecc12012-06-10 08:00:26 +00007021 LastPromotedArithmeticType = 11;
7022 static const unsigned NumArithmeticTypes = 20;
John McCall52872982010-11-13 05:51:15 +00007023
Chandler Carruthc6586e52010-12-12 10:35:00 +00007024 /// \brief Get the canonical type for a given arithmetic type index.
7025 CanQualType getArithmeticType(unsigned index) {
7026 assert(index < NumArithmeticTypes);
7027 static CanQualType ASTContext::* const
7028 ArithmeticTypes[NumArithmeticTypes] = {
7029 // Start of promoted types.
7030 &ASTContext::FloatTy,
7031 &ASTContext::DoubleTy,
7032 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00007033
Chandler Carruthc6586e52010-12-12 10:35:00 +00007034 // Start of integral types.
7035 &ASTContext::IntTy,
7036 &ASTContext::LongTy,
7037 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007038 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007039 &ASTContext::UnsignedIntTy,
7040 &ASTContext::UnsignedLongTy,
7041 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007042 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007043 // End of promoted types.
7044
7045 &ASTContext::BoolTy,
7046 &ASTContext::CharTy,
7047 &ASTContext::WCharTy,
7048 &ASTContext::Char16Ty,
7049 &ASTContext::Char32Ty,
7050 &ASTContext::SignedCharTy,
7051 &ASTContext::ShortTy,
7052 &ASTContext::UnsignedCharTy,
7053 &ASTContext::UnsignedShortTy,
7054 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00007055 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00007056 };
7057 return S.Context.*ArithmeticTypes[index];
7058 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007059
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007060 /// \brief Gets the canonical type resulting from the usual arithemetic
7061 /// converions for the given arithmetic types.
7062 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7063 // Accelerator table for performing the usual arithmetic conversions.
7064 // The rules are basically:
7065 // - if either is floating-point, use the wider floating-point
7066 // - if same signedness, use the higher rank
7067 // - if same size, use unsigned of the higher rank
7068 // - use the larger type
7069 // These rules, together with the axiom that higher ranks are
7070 // never smaller, are sufficient to precompute all of these results
7071 // *except* when dealing with signed types of higher rank.
7072 // (we could precompute SLL x UI for all known platforms, but it's
7073 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00007074 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007075 enum PromotedType {
Richard Smith521ecc12012-06-10 08:00:26 +00007076 Dep=-1,
7077 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007078 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00007079 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007080 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00007081/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7082/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7083/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7084/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7085/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7086/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7087/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7088/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7089/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7090/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7091/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007092 };
7093
7094 assert(L < LastPromotedArithmeticType);
7095 assert(R < LastPromotedArithmeticType);
7096 int Idx = ConversionsTable[L][R];
7097
7098 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007099 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007100
7101 // Slow path: we need to compare widths.
7102 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007103 CanQualType LT = getArithmeticType(L),
7104 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007105 unsigned LW = S.Context.getIntWidth(LT),
7106 RW = S.Context.getIntWidth(RT);
7107
7108 // If they're different widths, use the signed type.
7109 if (LW > RW) return LT;
7110 else if (LW < RW) return RT;
7111
7112 // Otherwise, use the unsigned type of the signed type's rank.
7113 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7114 assert(L == SLL || R == SLL);
7115 return S.Context.UnsignedLongLongTy;
7116 }
7117
Chandler Carruth5659c0c2010-12-12 09:22:45 +00007118 /// \brief Helper method to factor out the common pattern of adding overloads
7119 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007120 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007121 bool HasVolatile,
7122 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007123 QualType ParamTypes[2] = {
7124 S.Context.getLValueReferenceType(CandidateTy),
7125 S.Context.IntTy
7126 };
7127
7128 // Non-volatile version.
Richard Smithe54c3072013-05-05 15:51:06 +00007129 if (Args.size() == 1)
7130 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007131 else
Richard Smithe54c3072013-05-05 15:51:06 +00007132 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007133
7134 // Use a heuristic to reduce number of builtin candidates in the set:
7135 // add volatile version only if there are conversions to a volatile type.
7136 if (HasVolatile) {
7137 ParamTypes[0] =
7138 S.Context.getLValueReferenceType(
7139 S.Context.getVolatileType(CandidateTy));
Richard Smithe54c3072013-05-05 15:51:06 +00007140 if (Args.size() == 1)
7141 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007142 else
Richard Smithe54c3072013-05-05 15:51:06 +00007143 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007144 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007145
7146 // Add restrict version only if there are conversions to a restrict type
7147 // and our candidate type is a non-restrict-qualified pointer.
7148 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7149 !CandidateTy.isRestrictQualified()) {
7150 ParamTypes[0]
7151 = S.Context.getLValueReferenceType(
7152 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smithe54c3072013-05-05 15:51:06 +00007153 if (Args.size() == 1)
7154 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007155 else
Richard Smithe54c3072013-05-05 15:51:06 +00007156 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007157
7158 if (HasVolatile) {
7159 ParamTypes[0]
7160 = S.Context.getLValueReferenceType(
7161 S.Context.getCVRQualifiedType(CandidateTy,
7162 (Qualifiers::Volatile |
7163 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007164 if (Args.size() == 1)
7165 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007166 else
Richard Smithe54c3072013-05-05 15:51:06 +00007167 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007168 }
7169 }
7170
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007171 }
7172
7173public:
7174 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007175 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007176 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007177 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007178 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007179 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007180 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007181 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007182 HasArithmeticOrEnumeralCandidateType(
7183 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007184 CandidateTypes(CandidateTypes),
7185 CandidateSet(CandidateSet) {
7186 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007187 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007188 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007189 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007190 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007191 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007192 assert(getArithmeticType(FirstPromotedArithmeticType)
7193 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007194 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007195 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007196 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007197 "Invalid last promoted arithmetic type");
7198 }
7199
7200 // C++ [over.built]p3:
7201 //
7202 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7203 // is either volatile or empty, there exist candidate operator
7204 // functions of the form
7205 //
7206 // VQ T& operator++(VQ T&);
7207 // T operator++(VQ T&, int);
7208 //
7209 // C++ [over.built]p4:
7210 //
7211 // For every pair (T, VQ), where T is an arithmetic type other
7212 // than bool, and VQ is either volatile or empty, there exist
7213 // candidate operator functions of the form
7214 //
7215 // VQ T& operator--(VQ T&);
7216 // T operator--(VQ T&, int);
7217 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007218 if (!HasArithmeticOrEnumeralCandidateType)
7219 return;
7220
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007221 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7222 Arith < NumArithmeticTypes; ++Arith) {
7223 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007224 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007225 VisibleTypeConversionsQuals.hasVolatile(),
7226 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007227 }
7228 }
7229
7230 // C++ [over.built]p5:
7231 //
7232 // For every pair (T, VQ), where T is a cv-qualified or
7233 // cv-unqualified object type, and VQ is either volatile or
7234 // empty, there exist candidate operator functions of the form
7235 //
7236 // T*VQ& operator++(T*VQ&);
7237 // T*VQ& operator--(T*VQ&);
7238 // T* operator++(T*VQ&, int);
7239 // T* operator--(T*VQ&, int);
7240 void addPlusPlusMinusMinusPointerOverloads() {
7241 for (BuiltinCandidateTypeSet::iterator
7242 Ptr = CandidateTypes[0].pointer_begin(),
7243 PtrEnd = CandidateTypes[0].pointer_end();
7244 Ptr != PtrEnd; ++Ptr) {
7245 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007246 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007247 continue;
7248
7249 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007250 (!(*Ptr).isVolatileQualified() &&
7251 VisibleTypeConversionsQuals.hasVolatile()),
7252 (!(*Ptr).isRestrictQualified() &&
7253 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007254 }
7255 }
7256
7257 // C++ [over.built]p6:
7258 // For every cv-qualified or cv-unqualified object type T, there
7259 // exist candidate operator functions of the form
7260 //
7261 // T& operator*(T*);
7262 //
7263 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007264 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007265 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007266 // T& operator*(T*);
7267 void addUnaryStarPointerOverloads() {
7268 for (BuiltinCandidateTypeSet::iterator
7269 Ptr = CandidateTypes[0].pointer_begin(),
7270 PtrEnd = CandidateTypes[0].pointer_end();
7271 Ptr != PtrEnd; ++Ptr) {
7272 QualType ParamTy = *Ptr;
7273 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007274 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7275 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007276
Douglas Gregor02824322011-01-26 19:30:28 +00007277 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7278 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7279 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007280
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007281 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smithe54c3072013-05-05 15:51:06 +00007282 &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007283 }
7284 }
7285
7286 // C++ [over.built]p9:
7287 // For every promoted arithmetic type T, there exist candidate
7288 // operator functions of the form
7289 //
7290 // T operator+(T);
7291 // T operator-(T);
7292 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007293 if (!HasArithmeticOrEnumeralCandidateType)
7294 return;
7295
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007296 for (unsigned Arith = FirstPromotedArithmeticType;
7297 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007298 QualType ArithTy = getArithmeticType(Arith);
Richard Smithe54c3072013-05-05 15:51:06 +00007299 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007300 }
7301
7302 // Extension: We also add these operators for vector types.
7303 for (BuiltinCandidateTypeSet::iterator
7304 Vec = CandidateTypes[0].vector_begin(),
7305 VecEnd = CandidateTypes[0].vector_end();
7306 Vec != VecEnd; ++Vec) {
7307 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007308 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007309 }
7310 }
7311
7312 // C++ [over.built]p8:
7313 // For every type T, there exist candidate operator functions of
7314 // the form
7315 //
7316 // T* operator+(T*);
7317 void addUnaryPlusPointerOverloads() {
7318 for (BuiltinCandidateTypeSet::iterator
7319 Ptr = CandidateTypes[0].pointer_begin(),
7320 PtrEnd = CandidateTypes[0].pointer_end();
7321 Ptr != PtrEnd; ++Ptr) {
7322 QualType ParamTy = *Ptr;
Richard Smithe54c3072013-05-05 15:51:06 +00007323 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007324 }
7325 }
7326
7327 // C++ [over.built]p10:
7328 // For every promoted integral type T, there exist candidate
7329 // operator functions of the form
7330 //
7331 // T operator~(T);
7332 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007333 if (!HasArithmeticOrEnumeralCandidateType)
7334 return;
7335
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007336 for (unsigned Int = FirstPromotedIntegralType;
7337 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007338 QualType IntTy = getArithmeticType(Int);
Richard Smithe54c3072013-05-05 15:51:06 +00007339 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007340 }
7341
7342 // Extension: We also add this operator for vector types.
7343 for (BuiltinCandidateTypeSet::iterator
7344 Vec = CandidateTypes[0].vector_begin(),
7345 VecEnd = CandidateTypes[0].vector_end();
7346 Vec != VecEnd; ++Vec) {
7347 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007348 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007349 }
7350 }
7351
7352 // C++ [over.match.oper]p16:
7353 // For every pointer to member type T, there exist candidate operator
7354 // functions of the form
7355 //
7356 // bool operator==(T,T);
7357 // bool operator!=(T,T);
7358 void addEqualEqualOrNotEqualMemberPointerOverloads() {
7359 /// Set of (canonical) types that we've already handled.
7360 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7361
Richard Smithe54c3072013-05-05 15:51:06 +00007362 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007363 for (BuiltinCandidateTypeSet::iterator
7364 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7365 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7366 MemPtr != MemPtrEnd;
7367 ++MemPtr) {
7368 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007369 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007370 continue;
7371
7372 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007373 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007374 }
7375 }
7376 }
7377
7378 // C++ [over.built]p15:
7379 //
Douglas Gregor80af3132011-05-21 23:15:46 +00007380 // For every T, where T is an enumeration type, a pointer type, or
7381 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007382 //
7383 // bool operator<(T, T);
7384 // bool operator>(T, T);
7385 // bool operator<=(T, T);
7386 // bool operator>=(T, T);
7387 // bool operator==(T, T);
7388 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007389 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007390 // C++ [over.match.oper]p3:
7391 // [...]the built-in candidates include all of the candidate operator
7392 // functions defined in 13.6 that, compared to the given operator, [...]
7393 // do not have the same parameter-type-list as any non-template non-member
7394 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007395 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007396 // Note that in practice, this only affects enumeration types because there
7397 // aren't any built-in candidates of record type, and a user-defined operator
7398 // must have an operand of record or enumeration type. Also, the only other
7399 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007400 // cannot be overloaded for enumeration types, so this is the only place
7401 // where we must suppress candidates like this.
7402 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7403 UserDefinedBinaryOperators;
7404
Richard Smithe54c3072013-05-05 15:51:06 +00007405 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007406 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7407 CandidateTypes[ArgIdx].enumeration_end()) {
7408 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7409 CEnd = CandidateSet.end();
7410 C != CEnd; ++C) {
7411 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7412 continue;
7413
Eli Friedman14f082b2012-09-18 21:52:24 +00007414 if (C->Function->isFunctionTemplateSpecialization())
7415 continue;
7416
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007417 QualType FirstParamType =
7418 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7419 QualType SecondParamType =
7420 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7421
7422 // Skip if either parameter isn't of enumeral type.
7423 if (!FirstParamType->isEnumeralType() ||
7424 !SecondParamType->isEnumeralType())
7425 continue;
7426
7427 // Add this operator to the set of known user-defined operators.
7428 UserDefinedBinaryOperators.insert(
7429 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7430 S.Context.getCanonicalType(SecondParamType)));
7431 }
7432 }
7433 }
7434
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007435 /// Set of (canonical) types that we've already handled.
7436 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7437
Richard Smithe54c3072013-05-05 15:51:06 +00007438 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007439 for (BuiltinCandidateTypeSet::iterator
7440 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7441 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7442 Ptr != PtrEnd; ++Ptr) {
7443 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007444 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007445 continue;
7446
7447 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007448 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007449 }
7450 for (BuiltinCandidateTypeSet::iterator
7451 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7452 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7453 Enum != EnumEnd; ++Enum) {
7454 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7455
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007456 // Don't add the same builtin candidate twice, or if a user defined
7457 // candidate exists.
David Blaikie82e95a32014-11-19 07:49:47 +00007458 if (!AddedTypes.insert(CanonType).second ||
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007459 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7460 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007461 continue;
7462
7463 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007464 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007465 }
Douglas Gregor80af3132011-05-21 23:15:46 +00007466
7467 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7468 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
David Blaikie82e95a32014-11-19 07:49:47 +00007469 if (AddedTypes.insert(NullPtrTy).second &&
Richard Smithe54c3072013-05-05 15:51:06 +00007470 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor80af3132011-05-21 23:15:46 +00007471 NullPtrTy))) {
7472 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007473 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor80af3132011-05-21 23:15:46 +00007474 CandidateSet);
7475 }
7476 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007477 }
7478 }
7479
7480 // C++ [over.built]p13:
7481 //
7482 // For every cv-qualified or cv-unqualified object type T
7483 // there exist candidate operator functions of the form
7484 //
7485 // T* operator+(T*, ptrdiff_t);
7486 // T& operator[](T*, ptrdiff_t); [BELOW]
7487 // T* operator-(T*, ptrdiff_t);
7488 // T* operator+(ptrdiff_t, T*);
7489 // T& operator[](ptrdiff_t, T*); [BELOW]
7490 //
7491 // C++ [over.built]p14:
7492 //
7493 // For every T, where T is a pointer to object type, there
7494 // exist candidate operator functions of the form
7495 //
7496 // ptrdiff_t operator-(T, T);
7497 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7498 /// Set of (canonical) types that we've already handled.
7499 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7500
7501 for (int Arg = 0; Arg < 2; ++Arg) {
7502 QualType AsymetricParamTypes[2] = {
7503 S.Context.getPointerDiffType(),
7504 S.Context.getPointerDiffType(),
7505 };
7506 for (BuiltinCandidateTypeSet::iterator
7507 Ptr = CandidateTypes[Arg].pointer_begin(),
7508 PtrEnd = CandidateTypes[Arg].pointer_end();
7509 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00007510 QualType PointeeTy = (*Ptr)->getPointeeType();
7511 if (!PointeeTy->isObjectType())
7512 continue;
7513
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007514 AsymetricParamTypes[Arg] = *Ptr;
7515 if (Arg == 0 || Op == OO_Plus) {
7516 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7517 // T* operator+(ptrdiff_t, T*);
Richard Smithe54c3072013-05-05 15:51:06 +00007518 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007519 }
7520 if (Op == OO_Minus) {
7521 // ptrdiff_t operator-(T, T);
David Blaikie82e95a32014-11-19 07:49:47 +00007522 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007523 continue;
7524
7525 QualType ParamTypes[2] = { *Ptr, *Ptr };
7526 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smithe54c3072013-05-05 15:51:06 +00007527 Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007528 }
7529 }
7530 }
7531 }
7532
7533 // C++ [over.built]p12:
7534 //
7535 // For every pair of promoted arithmetic types L and R, there
7536 // exist candidate operator functions of the form
7537 //
7538 // LR operator*(L, R);
7539 // LR operator/(L, R);
7540 // LR operator+(L, R);
7541 // LR operator-(L, R);
7542 // bool operator<(L, R);
7543 // bool operator>(L, R);
7544 // bool operator<=(L, R);
7545 // bool operator>=(L, R);
7546 // bool operator==(L, R);
7547 // bool operator!=(L, R);
7548 //
7549 // where LR is the result of the usual arithmetic conversions
7550 // between types L and R.
7551 //
7552 // C++ [over.built]p24:
7553 //
7554 // For every pair of promoted arithmetic types L and R, there exist
7555 // candidate operator functions of the form
7556 //
7557 // LR operator?(bool, L, R);
7558 //
7559 // where LR is the result of the usual arithmetic conversions
7560 // between types L and R.
7561 // Our candidates ignore the first parameter.
7562 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007563 if (!HasArithmeticOrEnumeralCandidateType)
7564 return;
7565
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007566 for (unsigned Left = FirstPromotedArithmeticType;
7567 Left < LastPromotedArithmeticType; ++Left) {
7568 for (unsigned Right = FirstPromotedArithmeticType;
7569 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007570 QualType LandR[2] = { getArithmeticType(Left),
7571 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007572 QualType Result =
7573 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007574 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007575 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007576 }
7577 }
7578
7579 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7580 // conditional operator for vector types.
7581 for (BuiltinCandidateTypeSet::iterator
7582 Vec1 = CandidateTypes[0].vector_begin(),
7583 Vec1End = CandidateTypes[0].vector_end();
7584 Vec1 != Vec1End; ++Vec1) {
7585 for (BuiltinCandidateTypeSet::iterator
7586 Vec2 = CandidateTypes[1].vector_begin(),
7587 Vec2End = CandidateTypes[1].vector_end();
7588 Vec2 != Vec2End; ++Vec2) {
7589 QualType LandR[2] = { *Vec1, *Vec2 };
7590 QualType Result = S.Context.BoolTy;
7591 if (!isComparison) {
7592 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7593 Result = *Vec1;
7594 else
7595 Result = *Vec2;
7596 }
7597
Richard Smithe54c3072013-05-05 15:51:06 +00007598 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007599 }
7600 }
7601 }
7602
7603 // C++ [over.built]p17:
7604 //
7605 // For every pair of promoted integral types L and R, there
7606 // exist candidate operator functions of the form
7607 //
7608 // LR operator%(L, R);
7609 // LR operator&(L, R);
7610 // LR operator^(L, R);
7611 // LR operator|(L, R);
7612 // L operator<<(L, R);
7613 // L operator>>(L, R);
7614 //
7615 // where LR is the result of the usual arithmetic conversions
7616 // between types L and R.
7617 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007618 if (!HasArithmeticOrEnumeralCandidateType)
7619 return;
7620
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007621 for (unsigned Left = FirstPromotedIntegralType;
7622 Left < LastPromotedIntegralType; ++Left) {
7623 for (unsigned Right = FirstPromotedIntegralType;
7624 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007625 QualType LandR[2] = { getArithmeticType(Left),
7626 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007627 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7628 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007629 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007630 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007631 }
7632 }
7633 }
7634
7635 // C++ [over.built]p20:
7636 //
7637 // For every pair (T, VQ), where T is an enumeration or
7638 // pointer to member type and VQ is either volatile or
7639 // empty, there exist candidate operator functions of the form
7640 //
7641 // VQ T& operator=(VQ T&, T);
7642 void addAssignmentMemberPointerOrEnumeralOverloads() {
7643 /// Set of (canonical) types that we've already handled.
7644 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7645
7646 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7647 for (BuiltinCandidateTypeSet::iterator
7648 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7649 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7650 Enum != EnumEnd; ++Enum) {
David Blaikie82e95a32014-11-19 07:49:47 +00007651 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007652 continue;
7653
Richard Smithe54c3072013-05-05 15:51:06 +00007654 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007655 }
7656
7657 for (BuiltinCandidateTypeSet::iterator
7658 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7659 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7660 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00007661 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007662 continue;
7663
Richard Smithe54c3072013-05-05 15:51:06 +00007664 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007665 }
7666 }
7667 }
7668
7669 // C++ [over.built]p19:
7670 //
7671 // For every pair (T, VQ), where T is any type and VQ is either
7672 // volatile or empty, there exist candidate operator functions
7673 // of the form
7674 //
7675 // T*VQ& operator=(T*VQ&, T*);
7676 //
7677 // C++ [over.built]p21:
7678 //
7679 // For every pair (T, VQ), where T is a cv-qualified or
7680 // cv-unqualified object type and VQ is either volatile or
7681 // empty, there exist candidate operator functions of the form
7682 //
7683 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7684 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7685 void addAssignmentPointerOverloads(bool isEqualOp) {
7686 /// Set of (canonical) types that we've already handled.
7687 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7688
7689 for (BuiltinCandidateTypeSet::iterator
7690 Ptr = CandidateTypes[0].pointer_begin(),
7691 PtrEnd = CandidateTypes[0].pointer_end();
7692 Ptr != PtrEnd; ++Ptr) {
7693 // If this is operator=, keep track of the builtin candidates we added.
7694 if (isEqualOp)
7695 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007696 else if (!(*Ptr)->getPointeeType()->isObjectType())
7697 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007698
7699 // non-volatile version
7700 QualType ParamTypes[2] = {
7701 S.Context.getLValueReferenceType(*Ptr),
7702 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7703 };
Richard Smithe54c3072013-05-05 15:51:06 +00007704 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007705 /*IsAssigmentOperator=*/ isEqualOp);
7706
Douglas Gregor5bee2582012-06-04 00:15:09 +00007707 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7708 VisibleTypeConversionsQuals.hasVolatile();
7709 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007710 // volatile version
7711 ParamTypes[0] =
7712 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007713 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007714 /*IsAssigmentOperator=*/isEqualOp);
7715 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007716
7717 if (!(*Ptr).isRestrictQualified() &&
7718 VisibleTypeConversionsQuals.hasRestrict()) {
7719 // restrict version
7720 ParamTypes[0]
7721 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007722 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007723 /*IsAssigmentOperator=*/isEqualOp);
7724
7725 if (NeedVolatile) {
7726 // volatile restrict version
7727 ParamTypes[0]
7728 = S.Context.getLValueReferenceType(
7729 S.Context.getCVRQualifiedType(*Ptr,
7730 (Qualifiers::Volatile |
7731 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007732 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007733 /*IsAssigmentOperator=*/isEqualOp);
7734 }
7735 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007736 }
7737
7738 if (isEqualOp) {
7739 for (BuiltinCandidateTypeSet::iterator
7740 Ptr = CandidateTypes[1].pointer_begin(),
7741 PtrEnd = CandidateTypes[1].pointer_end();
7742 Ptr != PtrEnd; ++Ptr) {
7743 // Make sure we don't add the same candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007744 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007745 continue;
7746
Chandler Carruth8e543b32010-12-12 08:17:55 +00007747 QualType ParamTypes[2] = {
7748 S.Context.getLValueReferenceType(*Ptr),
7749 *Ptr,
7750 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007751
7752 // non-volatile version
Richard Smithe54c3072013-05-05 15:51:06 +00007753 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007754 /*IsAssigmentOperator=*/true);
7755
Douglas Gregor5bee2582012-06-04 00:15:09 +00007756 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7757 VisibleTypeConversionsQuals.hasVolatile();
7758 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007759 // volatile version
7760 ParamTypes[0] =
7761 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007762 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7763 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007764 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007765
7766 if (!(*Ptr).isRestrictQualified() &&
7767 VisibleTypeConversionsQuals.hasRestrict()) {
7768 // restrict version
7769 ParamTypes[0]
7770 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007771 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7772 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007773
7774 if (NeedVolatile) {
7775 // volatile restrict version
7776 ParamTypes[0]
7777 = S.Context.getLValueReferenceType(
7778 S.Context.getCVRQualifiedType(*Ptr,
7779 (Qualifiers::Volatile |
7780 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007781 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7782 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007783 }
7784 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007785 }
7786 }
7787 }
7788
7789 // C++ [over.built]p18:
7790 //
7791 // For every triple (L, VQ, R), where L is an arithmetic type,
7792 // VQ is either volatile or empty, and R is a promoted
7793 // arithmetic type, there exist candidate operator functions of
7794 // the form
7795 //
7796 // VQ L& operator=(VQ L&, R);
7797 // VQ L& operator*=(VQ L&, R);
7798 // VQ L& operator/=(VQ L&, R);
7799 // VQ L& operator+=(VQ L&, R);
7800 // VQ L& operator-=(VQ L&, R);
7801 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007802 if (!HasArithmeticOrEnumeralCandidateType)
7803 return;
7804
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007805 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7806 for (unsigned Right = FirstPromotedArithmeticType;
7807 Right < LastPromotedArithmeticType; ++Right) {
7808 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007809 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007810
7811 // Add this built-in operator as a candidate (VQ is empty).
7812 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007813 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007814 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007815 /*IsAssigmentOperator=*/isEqualOp);
7816
7817 // Add this built-in operator as a candidate (VQ is 'volatile').
7818 if (VisibleTypeConversionsQuals.hasVolatile()) {
7819 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007820 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007821 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007822 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007823 /*IsAssigmentOperator=*/isEqualOp);
7824 }
7825 }
7826 }
7827
7828 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7829 for (BuiltinCandidateTypeSet::iterator
7830 Vec1 = CandidateTypes[0].vector_begin(),
7831 Vec1End = CandidateTypes[0].vector_end();
7832 Vec1 != Vec1End; ++Vec1) {
7833 for (BuiltinCandidateTypeSet::iterator
7834 Vec2 = CandidateTypes[1].vector_begin(),
7835 Vec2End = CandidateTypes[1].vector_end();
7836 Vec2 != Vec2End; ++Vec2) {
7837 QualType ParamTypes[2];
7838 ParamTypes[1] = *Vec2;
7839 // Add this built-in operator as a candidate (VQ is empty).
7840 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smithe54c3072013-05-05 15:51:06 +00007841 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007842 /*IsAssigmentOperator=*/isEqualOp);
7843
7844 // Add this built-in operator as a candidate (VQ is 'volatile').
7845 if (VisibleTypeConversionsQuals.hasVolatile()) {
7846 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7847 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007848 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007849 /*IsAssigmentOperator=*/isEqualOp);
7850 }
7851 }
7852 }
7853 }
7854
7855 // C++ [over.built]p22:
7856 //
7857 // For every triple (L, VQ, R), where L is an integral type, VQ
7858 // is either volatile or empty, and R is a promoted integral
7859 // type, there exist candidate operator functions of the form
7860 //
7861 // VQ L& operator%=(VQ L&, R);
7862 // VQ L& operator<<=(VQ L&, R);
7863 // VQ L& operator>>=(VQ L&, R);
7864 // VQ L& operator&=(VQ L&, R);
7865 // VQ L& operator^=(VQ L&, R);
7866 // VQ L& operator|=(VQ L&, R);
7867 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007868 if (!HasArithmeticOrEnumeralCandidateType)
7869 return;
7870
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007871 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7872 for (unsigned Right = FirstPromotedIntegralType;
7873 Right < LastPromotedIntegralType; ++Right) {
7874 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007875 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007876
7877 // Add this built-in operator as a candidate (VQ is empty).
7878 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007879 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007880 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007881 if (VisibleTypeConversionsQuals.hasVolatile()) {
7882 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00007883 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007884 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7885 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007886 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007887 }
7888 }
7889 }
7890 }
7891
7892 // C++ [over.operator]p23:
7893 //
7894 // There also exist candidate operator functions of the form
7895 //
7896 // bool operator!(bool);
7897 // bool operator&&(bool, bool);
7898 // bool operator||(bool, bool);
7899 void addExclaimOverload() {
7900 QualType ParamTy = S.Context.BoolTy;
Richard Smithe54c3072013-05-05 15:51:06 +00007901 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007902 /*IsAssignmentOperator=*/false,
7903 /*NumContextualBoolArguments=*/1);
7904 }
7905 void addAmpAmpOrPipePipeOverload() {
7906 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007907 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007908 /*IsAssignmentOperator=*/false,
7909 /*NumContextualBoolArguments=*/2);
7910 }
7911
7912 // C++ [over.built]p13:
7913 //
7914 // For every cv-qualified or cv-unqualified object type T there
7915 // exist candidate operator functions of the form
7916 //
7917 // T* operator+(T*, ptrdiff_t); [ABOVE]
7918 // T& operator[](T*, ptrdiff_t);
7919 // T* operator-(T*, ptrdiff_t); [ABOVE]
7920 // T* operator+(ptrdiff_t, T*); [ABOVE]
7921 // T& operator[](ptrdiff_t, T*);
7922 void addSubscriptOverloads() {
7923 for (BuiltinCandidateTypeSet::iterator
7924 Ptr = CandidateTypes[0].pointer_begin(),
7925 PtrEnd = CandidateTypes[0].pointer_end();
7926 Ptr != PtrEnd; ++Ptr) {
7927 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7928 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007929 if (!PointeeType->isObjectType())
7930 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007931
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007932 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7933
7934 // T& operator[](T*, ptrdiff_t)
Richard Smithe54c3072013-05-05 15:51:06 +00007935 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007936 }
7937
7938 for (BuiltinCandidateTypeSet::iterator
7939 Ptr = CandidateTypes[1].pointer_begin(),
7940 PtrEnd = CandidateTypes[1].pointer_end();
7941 Ptr != PtrEnd; ++Ptr) {
7942 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7943 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007944 if (!PointeeType->isObjectType())
7945 continue;
7946
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007947 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7948
7949 // T& operator[](ptrdiff_t, T*)
Richard Smithe54c3072013-05-05 15:51:06 +00007950 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007951 }
7952 }
7953
7954 // C++ [over.built]p11:
7955 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7956 // C1 is the same type as C2 or is a derived class of C2, T is an object
7957 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7958 // there exist candidate operator functions of the form
7959 //
7960 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7961 //
7962 // where CV12 is the union of CV1 and CV2.
7963 void addArrowStarOverloads() {
7964 for (BuiltinCandidateTypeSet::iterator
7965 Ptr = CandidateTypes[0].pointer_begin(),
7966 PtrEnd = CandidateTypes[0].pointer_end();
7967 Ptr != PtrEnd; ++Ptr) {
7968 QualType C1Ty = (*Ptr);
7969 QualType C1;
7970 QualifierCollector Q1;
7971 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7972 if (!isa<RecordType>(C1))
7973 continue;
7974 // heuristic to reduce number of builtin candidates in the set.
7975 // Add volatile/restrict version only if there are conversions to a
7976 // volatile/restrict type.
7977 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7978 continue;
7979 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7980 continue;
7981 for (BuiltinCandidateTypeSet::iterator
7982 MemPtr = CandidateTypes[1].member_pointer_begin(),
7983 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7984 MemPtr != MemPtrEnd; ++MemPtr) {
7985 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7986 QualType C2 = QualType(mptr->getClass(), 0);
7987 C2 = C2.getUnqualifiedType();
7988 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7989 break;
7990 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7991 // build CV12 T&
7992 QualType T = mptr->getPointeeType();
7993 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7994 T.isVolatileQualified())
7995 continue;
7996 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7997 T.isRestrictQualified())
7998 continue;
7999 T = Q1.apply(S.Context, T);
8000 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smithe54c3072013-05-05 15:51:06 +00008001 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008002 }
8003 }
8004 }
8005
8006 // Note that we don't consider the first argument, since it has been
8007 // contextually converted to bool long ago. The candidates below are
8008 // therefore added as binary.
8009 //
8010 // C++ [over.built]p25:
8011 // For every type T, where T is a pointer, pointer-to-member, or scoped
8012 // enumeration type, there exist candidate operator functions of the form
8013 //
8014 // T operator?(bool, T, T);
8015 //
8016 void addConditionalOperatorOverloads() {
8017 /// Set of (canonical) types that we've already handled.
8018 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8019
8020 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8021 for (BuiltinCandidateTypeSet::iterator
8022 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8023 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8024 Ptr != PtrEnd; ++Ptr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008025 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008026 continue;
8027
8028 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00008029 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008030 }
8031
8032 for (BuiltinCandidateTypeSet::iterator
8033 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8034 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8035 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008036 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008037 continue;
8038
8039 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00008040 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008041 }
8042
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008043 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008044 for (BuiltinCandidateTypeSet::iterator
8045 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8046 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8047 Enum != EnumEnd; ++Enum) {
8048 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8049 continue;
8050
David Blaikie82e95a32014-11-19 07:49:47 +00008051 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008052 continue;
8053
8054 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00008055 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008056 }
8057 }
8058 }
8059 }
8060};
8061
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008062} // end anonymous namespace
8063
8064/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8065/// operator overloads to the candidate set (C++ [over.built]), based
8066/// on the operator @p Op and the arguments given. For example, if the
8067/// operator is a binary '+', this routine might add "int
8068/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00008069void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8070 SourceLocation OpLoc,
8071 ArrayRef<Expr *> Args,
8072 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00008073 // Find all of the types that the arguments can convert to, but only
8074 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00008075 // that make use of these types. Also record whether we encounter non-record
8076 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00008077 Qualifiers VisibleTypeConversionsQuals;
8078 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00008079 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00008080 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00008081
8082 bool HasNonRecordCandidateType = false;
8083 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008084 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00008085 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008086 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
8087 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8088 OpLoc,
8089 true,
8090 (Op == OO_Exclaim ||
8091 Op == OO_AmpAmp ||
8092 Op == OO_PipePipe),
8093 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00008094 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8095 CandidateTypes[ArgIdx].hasNonRecordTypes();
8096 HasArithmeticOrEnumeralCandidateType =
8097 HasArithmeticOrEnumeralCandidateType ||
8098 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008099 }
Douglas Gregora11693b2008-11-12 17:17:38 +00008100
Chandler Carruth00a38332010-12-13 01:44:01 +00008101 // Exit early when no non-record types have been added to the candidate set
8102 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008103 //
8104 // We can't exit early for !, ||, or &&, since there we have always have
8105 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008106 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008107 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00008108 return;
8109
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008110 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008111 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008112 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00008113 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008114 CandidateTypes, CandidateSet);
8115
8116 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00008117 switch (Op) {
8118 case OO_None:
8119 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00008120 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00008121
Chandler Carruth5184de02010-12-12 08:51:33 +00008122 case OO_New:
8123 case OO_Delete:
8124 case OO_Array_New:
8125 case OO_Array_Delete:
8126 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00008127 llvm_unreachable(
8128 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00008129
8130 case OO_Comma:
8131 case OO_Arrow:
8132 // C++ [over.match.oper]p3:
8133 // -- For the operator ',', the unary operator '&', or the
8134 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00008135 break;
8136
8137 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008138 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008139 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00008140 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00008141
8142 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008143 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008144 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008145 } else {
8146 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8147 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8148 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008149 break;
8150
Chandler Carruth5184de02010-12-12 08:51:33 +00008151 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008152 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008153 OpBuilder.addUnaryStarPointerOverloads();
8154 else
8155 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8156 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008157
Chandler Carruth5184de02010-12-12 08:51:33 +00008158 case OO_Slash:
8159 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008160 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008161
8162 case OO_PlusPlus:
8163 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008164 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8165 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008166 break;
8167
Douglas Gregor84605ae2009-08-24 13:43:27 +00008168 case OO_EqualEqual:
8169 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008170 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008171 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008172
Douglas Gregora11693b2008-11-12 17:17:38 +00008173 case OO_Less:
8174 case OO_Greater:
8175 case OO_LessEqual:
8176 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008177 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008178 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8179 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008180
Douglas Gregora11693b2008-11-12 17:17:38 +00008181 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008182 case OO_Caret:
8183 case OO_Pipe:
8184 case OO_LessLess:
8185 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008186 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008187 break;
8188
Chandler Carruth5184de02010-12-12 08:51:33 +00008189 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008190 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008191 // C++ [over.match.oper]p3:
8192 // -- For the operator ',', the unary operator '&', or the
8193 // operator '->', the built-in candidates set is empty.
8194 break;
8195
8196 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8197 break;
8198
8199 case OO_Tilde:
8200 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8201 break;
8202
Douglas Gregora11693b2008-11-12 17:17:38 +00008203 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008204 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008205 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008206
8207 case OO_PlusEqual:
8208 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008209 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008210 // Fall through.
8211
8212 case OO_StarEqual:
8213 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008214 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008215 break;
8216
8217 case OO_PercentEqual:
8218 case OO_LessLessEqual:
8219 case OO_GreaterGreaterEqual:
8220 case OO_AmpEqual:
8221 case OO_CaretEqual:
8222 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008223 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008224 break;
8225
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008226 case OO_Exclaim:
8227 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008228 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008229
Douglas Gregora11693b2008-11-12 17:17:38 +00008230 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008231 case OO_PipePipe:
8232 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008233 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008234
8235 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008236 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008237 break;
8238
8239 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008240 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008241 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008242
8243 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008244 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008245 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8246 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008247 }
8248}
8249
Douglas Gregore254f902009-02-04 00:32:51 +00008250/// \brief Add function candidates found via argument-dependent lookup
8251/// to the set of overloading candidates.
8252///
8253/// This routine performs argument-dependent name lookup based on the
8254/// given function name (which may also be an operator name) and adds
8255/// all of the overload candidates found by ADL to the overload
8256/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008257void
Douglas Gregore254f902009-02-04 00:32:51 +00008258Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smith100b24a2014-04-17 01:52:14 +00008259 SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008260 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008261 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008262 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008263 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008264 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008265
John McCall91f61fc2010-01-26 06:04:06 +00008266 // FIXME: This approach for uniquing ADL results (and removing
8267 // redundant candidates from the set) relies on pointer-equality,
8268 // which means we need to key off the canonical decl. However,
8269 // always going back to the canonical decl might not get us the
8270 // right set of default arguments. What default arguments are
8271 // we supposed to consider on ADL candidates, anyway?
8272
Douglas Gregorcabea402009-09-22 15:41:20 +00008273 // FIXME: Pass in the explicit template arguments?
Richard Smith100b24a2014-04-17 01:52:14 +00008274 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008275
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008276 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008277 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8278 CandEnd = CandidateSet.end();
8279 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008280 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008281 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008282 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008283 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008284 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008285
8286 // For each of the ADL candidates we found, add it to the overload
8287 // set.
John McCall8fe68082010-01-26 07:16:45 +00008288 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008289 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008290 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008291 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008292 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008293
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008294 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8295 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008296 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008297 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008298 FoundDecl, ExplicitTemplateArgs,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00008299 Args, CandidateSet, PartialOverloading);
Douglas Gregor15448f82009-06-27 21:05:07 +00008300 }
Douglas Gregore254f902009-02-04 00:32:51 +00008301}
8302
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008303/// isBetterOverloadCandidate - Determines whether the first overload
8304/// candidate is a better candidate than the second (C++ 13.3.3p1).
Richard Smith17c00b42014-11-12 01:24:00 +00008305bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8306 const OverloadCandidate &Cand2,
8307 SourceLocation Loc,
8308 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008309 // Define viable functions to be better candidates than non-viable
8310 // functions.
8311 if (!Cand2.Viable)
8312 return Cand1.Viable;
8313 else if (!Cand1.Viable)
8314 return false;
8315
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008316 // C++ [over.match.best]p1:
8317 //
8318 // -- if F is a static member function, ICS1(F) is defined such
8319 // that ICS1(F) is neither better nor worse than ICS1(G) for
8320 // any function G, and, symmetrically, ICS1(G) is neither
8321 // better nor worse than ICS1(F).
8322 unsigned StartArg = 0;
8323 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8324 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008325
Douglas Gregord3cb3562009-07-07 23:38:56 +00008326 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008327 // A viable function F1 is defined to be a better function than another
8328 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008329 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00008330 unsigned NumArgs = Cand1.NumConversions;
8331 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008332 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008333 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00008334 switch (CompareImplicitConversionSequences(S,
8335 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008336 Cand2.Conversions[ArgIdx])) {
8337 case ImplicitConversionSequence::Better:
8338 // Cand1 has a better conversion sequence.
8339 HasBetterConversion = true;
8340 break;
8341
8342 case ImplicitConversionSequence::Worse:
8343 // Cand1 can't be better than Cand2.
8344 return false;
8345
8346 case ImplicitConversionSequence::Indistinguishable:
8347 // Do nothing.
8348 break;
8349 }
8350 }
8351
Mike Stump11289f42009-09-09 15:08:12 +00008352 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008353 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008354 if (HasBetterConversion)
8355 return true;
8356
Douglas Gregora1f013e2008-11-07 22:36:19 +00008357 // -- the context is an initialization by user-defined conversion
8358 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8359 // from the return type of F1 to the destination type (i.e.,
8360 // the type of the entity being initialized) is a better
8361 // conversion sequence than the standard conversion sequence
8362 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00008363 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00008364 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00008365 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00008366 // First check whether we prefer one of the conversion functions over the
8367 // other. This only distinguishes the results in non-standard, extension
8368 // cases such as the conversion from a lambda closure type to a function
8369 // pointer or block.
Richard Smithec2748a2014-05-17 04:36:39 +00008370 ImplicitConversionSequence::CompareKind Result =
8371 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8372 if (Result == ImplicitConversionSequence::Indistinguishable)
8373 Result = CompareStandardConversionSequences(S,
8374 Cand1.FinalConversion,
8375 Cand2.FinalConversion);
Richard Smith6fdeaab2014-05-17 01:58:45 +00008376
Richard Smithec2748a2014-05-17 04:36:39 +00008377 if (Result != ImplicitConversionSequence::Indistinguishable)
8378 return Result == ImplicitConversionSequence::Better;
Richard Smith6fdeaab2014-05-17 01:58:45 +00008379
8380 // FIXME: Compare kind of reference binding if conversion functions
8381 // convert to a reference type used in direct reference binding, per
8382 // C++14 [over.match.best]p1 section 2 bullet 3.
8383 }
8384
8385 // -- F1 is a non-template function and F2 is a function template
8386 // specialization, or, if not that,
8387 bool Cand1IsSpecialization = Cand1.Function &&
8388 Cand1.Function->getPrimaryTemplate();
8389 bool Cand2IsSpecialization = Cand2.Function &&
8390 Cand2.Function->getPrimaryTemplate();
8391 if (Cand1IsSpecialization != Cand2IsSpecialization)
8392 return Cand2IsSpecialization;
8393
8394 // -- F1 and F2 are function template specializations, and the function
8395 // template for F1 is more specialized than the template for F2
8396 // according to the partial ordering rules described in 14.5.5.2, or,
8397 // if not that,
8398 if (Cand1IsSpecialization && Cand2IsSpecialization) {
8399 if (FunctionTemplateDecl *BetterTemplate
8400 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8401 Cand2.Function->getPrimaryTemplate(),
8402 Loc,
8403 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8404 : TPOC_Call,
8405 Cand1.ExplicitCallArguments,
8406 Cand2.ExplicitCallArguments))
8407 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregora1f013e2008-11-07 22:36:19 +00008408 }
8409
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008410 // Check for enable_if value-based overload resolution.
8411 if (Cand1.Function && Cand2.Function &&
8412 (Cand1.Function->hasAttr<EnableIfAttr>() ||
8413 Cand2.Function->hasAttr<EnableIfAttr>())) {
8414 // FIXME: The next several lines are just
8415 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8416 // instead of reverse order which is how they're stored in the AST.
8417 AttrVec Cand1Attrs;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008418 if (Cand1.Function->hasAttrs()) {
8419 Cand1Attrs = Cand1.Function->getAttrs();
Richard Smith9516eee2014-05-17 02:21:47 +00008420 Cand1Attrs.erase(std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(),
8421 IsNotEnableIfAttr),
8422 Cand1Attrs.end());
8423 std::reverse(Cand1Attrs.begin(), Cand1Attrs.end());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008424 }
8425
8426 AttrVec Cand2Attrs;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008427 if (Cand2.Function->hasAttrs()) {
8428 Cand2Attrs = Cand2.Function->getAttrs();
Richard Smith9516eee2014-05-17 02:21:47 +00008429 Cand2Attrs.erase(std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(),
8430 IsNotEnableIfAttr),
8431 Cand2Attrs.end());
8432 std::reverse(Cand2Attrs.begin(), Cand2Attrs.end());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008433 }
Richard Smith9516eee2014-05-17 02:21:47 +00008434
8435 // Candidate 1 is better if it has strictly more attributes and
8436 // the common sequence is identical.
8437 if (Cand1Attrs.size() <= Cand2Attrs.size())
8438 return false;
8439
8440 auto Cand1I = Cand1Attrs.begin();
8441 for (auto &Cand2A : Cand2Attrs) {
8442 auto &Cand1A = *Cand1I++;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008443 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
Richard Smith9516eee2014-05-17 02:21:47 +00008444 cast<EnableIfAttr>(Cand1A)->getCond()->Profile(Cand1ID,
8445 S.getASTContext(), true);
8446 cast<EnableIfAttr>(Cand2A)->getCond()->Profile(Cand2ID,
8447 S.getASTContext(), true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00008448 if (Cand1ID != Cand2ID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008449 return false;
8450 }
Richard Smith9516eee2014-05-17 02:21:47 +00008451
8452 return true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008453 }
8454
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008455 return false;
8456}
8457
Mike Stump11289f42009-09-09 15:08:12 +00008458/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008459/// within an overload candidate set.
8460///
James Dennettffad8b72012-06-22 08:10:18 +00008461/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008462/// which overload resolution occurs.
8463///
James Dennettffad8b72012-06-22 08:10:18 +00008464/// \param Best If overload resolution was successful or found a deleted
8465/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008466///
8467/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00008468OverloadingResult
8469OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008470 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00008471 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008472 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00008473 Best = end();
8474 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8475 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008476 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008477 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008478 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008479 }
8480
8481 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00008482 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008483 return OR_No_Viable_Function;
8484
8485 // Make sure that this function is better than every other viable
8486 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00008487 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00008488 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008489 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008490 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008491 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00008492 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008493 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00008494 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008495 }
Mike Stump11289f42009-09-09 15:08:12 +00008496
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008497 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00008498 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008499 (Best->Function->isDeleted() ||
8500 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00008501 return OR_Deleted;
8502
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008503 return OR_Success;
8504}
8505
John McCall53262c92010-01-12 02:15:36 +00008506namespace {
8507
8508enum OverloadCandidateKind {
8509 oc_function,
8510 oc_method,
8511 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00008512 oc_function_template,
8513 oc_method_template,
8514 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00008515 oc_implicit_default_constructor,
8516 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008517 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00008518 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008519 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00008520 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00008521};
8522
John McCalle1ac8d12010-01-13 00:25:19 +00008523OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8524 FunctionDecl *Fn,
8525 std::string &Description) {
8526 bool isTemplate = false;
8527
8528 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8529 isTemplate = true;
8530 Description = S.getTemplateArgumentBindingsText(
8531 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8532 }
John McCallfd0b2f82010-01-06 09:43:14 +00008533
8534 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00008535 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008536 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008537
Sebastian Redl08905022011-02-05 19:23:19 +00008538 if (Ctor->getInheritedConstructor())
8539 return oc_implicit_inherited_constructor;
8540
Alexis Hunt119c10e2011-05-25 23:16:36 +00008541 if (Ctor->isDefaultConstructor())
8542 return oc_implicit_default_constructor;
8543
8544 if (Ctor->isMoveConstructor())
8545 return oc_implicit_move_constructor;
8546
8547 assert(Ctor->isCopyConstructor() &&
8548 "unexpected sort of implicit constructor");
8549 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008550 }
8551
8552 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8553 // This actually gets spelled 'candidate function' for now, but
8554 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00008555 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008556 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00008557
Alexis Hunt119c10e2011-05-25 23:16:36 +00008558 if (Meth->isMoveAssignmentOperator())
8559 return oc_implicit_move_assignment;
8560
Douglas Gregor12695102012-02-10 08:36:38 +00008561 if (Meth->isCopyAssignmentOperator())
8562 return oc_implicit_copy_assignment;
8563
8564 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8565 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00008566 }
8567
John McCalle1ac8d12010-01-13 00:25:19 +00008568 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00008569}
8570
Larisse Voufo98b20f12013-07-19 23:00:19 +00008571void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
Sebastian Redl08905022011-02-05 19:23:19 +00008572 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8573 if (!Ctor) return;
8574
8575 Ctor = Ctor->getInheritedConstructor();
8576 if (!Ctor) return;
8577
8578 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8579}
8580
John McCall53262c92010-01-12 02:15:36 +00008581} // end anonymous namespace
8582
8583// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00008584void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00008585 std::string FnDesc;
8586 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00008587 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8588 << (unsigned) K << FnDesc;
8589 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8590 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00008591 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00008592}
8593
Nick Lewyckyed4265c2013-09-22 10:06:01 +00008594// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00008595// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00008596void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008597 assert(OverloadedExpr->getType() == Context.OverloadTy);
8598
8599 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8600 OverloadExpr *OvlExpr = Ovl.Expression;
8601
8602 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8603 IEnd = OvlExpr->decls_end();
8604 I != IEnd; ++I) {
8605 if (FunctionTemplateDecl *FunTmpl =
8606 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00008607 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008608 } else if (FunctionDecl *Fun
8609 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00008610 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008611 }
8612 }
8613}
8614
John McCall0d1da222010-01-12 00:44:57 +00008615/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8616/// "lead" diagnostic; it will be given two arguments, the source and
8617/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00008618void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8619 Sema &S,
8620 SourceLocation CaretLoc,
8621 const PartialDiagnostic &PDiag) const {
8622 S.Diag(CaretLoc, PDiag)
8623 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008624 // FIXME: The note limiting machinery is borrowed from
8625 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8626 // refactoring here.
8627 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8628 unsigned CandsShown = 0;
8629 AmbiguousConversionSequence::const_iterator I, E;
8630 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8631 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8632 break;
8633 ++CandsShown;
John McCall5c32be02010-08-24 20:38:10 +00008634 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00008635 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008636 if (I != E)
8637 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00008638}
8639
Richard Smith17c00b42014-11-12 01:24:00 +00008640static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
8641 unsigned I) {
John McCall6a61b522010-01-13 09:16:55 +00008642 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8643 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00008644 assert(Cand->Function && "for now, candidate must be a function");
8645 FunctionDecl *Fn = Cand->Function;
8646
8647 // There's a conversion slot for the object argument if this is a
8648 // non-constructor method. Note that 'I' corresponds the
8649 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00008650 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00008651 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00008652 if (I == 0)
8653 isObjectArgument = true;
8654 else
8655 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00008656 }
8657
John McCalle1ac8d12010-01-13 00:25:19 +00008658 std::string FnDesc;
8659 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8660
John McCall6a61b522010-01-13 09:16:55 +00008661 Expr *FromExpr = Conv.Bad.FromExpr;
8662 QualType FromTy = Conv.Bad.getFromType();
8663 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00008664
John McCallfb7ad0f2010-02-02 02:42:52 +00008665 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00008666 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00008667 Expr *E = FromExpr->IgnoreParens();
8668 if (isa<UnaryOperator>(E))
8669 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00008670 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00008671
8672 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8673 << (unsigned) FnKind << FnDesc
8674 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8675 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008676 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00008677 return;
8678 }
8679
John McCall6d174642010-01-23 08:10:49 +00008680 // Do some hand-waving analysis to see if the non-viability is due
8681 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00008682 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8683 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8684 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8685 CToTy = RT->getPointeeType();
8686 else {
8687 // TODO: detect and diagnose the full richness of const mismatches.
8688 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8689 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8690 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8691 }
8692
8693 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8694 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00008695 Qualifiers FromQs = CFromTy.getQualifiers();
8696 Qualifiers ToQs = CToTy.getQualifiers();
8697
8698 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8699 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8700 << (unsigned) FnKind << FnDesc
8701 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8702 << FromTy
8703 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8704 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008705 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008706 return;
8707 }
8708
John McCall31168b02011-06-15 23:02:42 +00008709 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008710 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00008711 << (unsigned) FnKind << FnDesc
8712 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8713 << FromTy
8714 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8715 << (unsigned) isObjectArgument << I+1;
8716 MaybeEmitInheritedConstructorNote(S, Fn);
8717 return;
8718 }
8719
Douglas Gregoraec25842011-04-26 23:16:46 +00008720 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8721 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8722 << (unsigned) FnKind << FnDesc
8723 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8724 << FromTy
8725 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8726 << (unsigned) isObjectArgument << I+1;
8727 MaybeEmitInheritedConstructorNote(S, Fn);
8728 return;
8729 }
8730
John McCall47000992010-01-14 03:28:57 +00008731 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8732 assert(CVR && "unexpected qualifiers mismatch");
8733
8734 if (isObjectArgument) {
8735 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8736 << (unsigned) FnKind << FnDesc
8737 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8738 << FromTy << (CVR - 1);
8739 } else {
8740 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8741 << (unsigned) FnKind << FnDesc
8742 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8743 << FromTy << (CVR - 1) << I+1;
8744 }
Sebastian Redl08905022011-02-05 19:23:19 +00008745 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008746 return;
8747 }
8748
Sebastian Redla72462c2011-09-24 17:48:32 +00008749 // Special diagnostic for failure to convert an initializer list, since
8750 // telling the user that it has type void is not useful.
8751 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8752 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8753 << (unsigned) FnKind << FnDesc
8754 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8755 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8756 MaybeEmitInheritedConstructorNote(S, Fn);
8757 return;
8758 }
8759
John McCall6d174642010-01-23 08:10:49 +00008760 // Diagnose references or pointers to incomplete types differently,
8761 // since it's far from impossible that the incompleteness triggered
8762 // the failure.
8763 QualType TempFromTy = FromTy.getNonReferenceType();
8764 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8765 TempFromTy = PTy->getPointeeType();
8766 if (TempFromTy->isIncompleteType()) {
8767 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8768 << (unsigned) FnKind << FnDesc
8769 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8770 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008771 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00008772 return;
8773 }
8774
Douglas Gregor56f2e342010-06-30 23:01:39 +00008775 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008776 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008777 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8778 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8779 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8780 FromPtrTy->getPointeeType()) &&
8781 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8782 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008783 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00008784 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008785 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008786 }
8787 } else if (const ObjCObjectPointerType *FromPtrTy
8788 = FromTy->getAs<ObjCObjectPointerType>()) {
8789 if (const ObjCObjectPointerType *ToPtrTy
8790 = ToTy->getAs<ObjCObjectPointerType>())
8791 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8792 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8793 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8794 FromPtrTy->getPointeeType()) &&
8795 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008796 BaseToDerivedConversion = 2;
8797 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008798 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8799 !FromTy->isIncompleteType() &&
8800 !ToRefTy->getPointeeType()->isIncompleteType() &&
8801 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8802 BaseToDerivedConversion = 3;
8803 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8804 ToTy.getNonReferenceType().getCanonicalType() ==
8805 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008806 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8807 << (unsigned) FnKind << FnDesc
8808 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8809 << (unsigned) isObjectArgument << I + 1;
8810 MaybeEmitInheritedConstructorNote(S, Fn);
8811 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008812 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008813 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008814
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008815 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008816 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008817 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00008818 << (unsigned) FnKind << FnDesc
8819 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008820 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008821 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008822 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00008823 return;
8824 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008825
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00008826 if (isa<ObjCObjectPointerType>(CFromTy) &&
8827 isa<PointerType>(CToTy)) {
8828 Qualifiers FromQs = CFromTy.getQualifiers();
8829 Qualifiers ToQs = CToTy.getQualifiers();
8830 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8831 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8832 << (unsigned) FnKind << FnDesc
8833 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8834 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8835 MaybeEmitInheritedConstructorNote(S, Fn);
8836 return;
8837 }
8838 }
8839
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008840 // Emit the generic diagnostic and, optionally, add the hints to it.
8841 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8842 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00008843 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008844 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8845 << (unsigned) (Cand->Fix.Kind);
8846
8847 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00008848 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8849 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008850 FDiag << *HI;
8851 S.Diag(Fn->getLocation(), FDiag);
8852
Sebastian Redl08905022011-02-05 19:23:19 +00008853 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00008854}
8855
Larisse Voufo98b20f12013-07-19 23:00:19 +00008856/// Additional arity mismatch diagnosis specific to a function overload
8857/// candidates. This is not covered by the more general DiagnoseArityMismatch()
8858/// over a candidate in any candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00008859static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8860 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00008861 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00008862 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008863
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008864 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00008865 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008866 // right number of arguments, because only overloaded operators have
8867 // the weird behavior of overloading member and non-member functions.
8868 // Just don't report anything.
8869 if (Fn->isInvalidDecl() &&
8870 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008871 return true;
8872
8873 if (NumArgs < MinParams) {
8874 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8875 (Cand->FailureKind == ovl_fail_bad_deduction &&
8876 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8877 } else {
8878 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8879 (Cand->FailureKind == ovl_fail_bad_deduction &&
8880 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8881 }
8882
8883 return false;
8884}
8885
8886/// General arity mismatch diagnosis over a candidate in a candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00008887static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008888 assert(isa<FunctionDecl>(D) &&
8889 "The templated declaration should at least be a function"
8890 " when diagnosing bad template argument deduction due to too many"
8891 " or too few arguments");
8892
8893 FunctionDecl *Fn = cast<FunctionDecl>(D);
8894
8895 // TODO: treat calls to a missing default constructor as a special case
8896 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8897 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008898
John McCall6a61b522010-01-13 09:16:55 +00008899 // at least / at most / exactly
8900 unsigned mode, modeCount;
8901 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00008902 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
8903 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00008904 mode = 0; // "at least"
8905 else
8906 mode = 2; // "exactly"
8907 modeCount = MinParams;
8908 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00008909 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00008910 mode = 1; // "at most"
8911 else
8912 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00008913 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00008914 }
8915
8916 std::string Description;
8917 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8918
Richard Smith10ff50d2012-05-11 05:16:41 +00008919 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8920 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Craig Topperc3ec1492014-05-26 06:22:03 +00008921 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8922 << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smith10ff50d2012-05-11 05:16:41 +00008923 else
8924 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Craig Topperc3ec1492014-05-26 06:22:03 +00008925 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8926 << mode << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00008927 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008928}
8929
Larisse Voufo98b20f12013-07-19 23:00:19 +00008930/// Arity mismatch diagnosis specific to a function overload candidate.
Richard Smith17c00b42014-11-12 01:24:00 +00008931static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8932 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008933 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
8934 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
8935}
Larisse Voufo47c08452013-07-19 22:53:23 +00008936
Richard Smith17c00b42014-11-12 01:24:00 +00008937static TemplateDecl *getDescribedTemplate(Decl *Templated) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008938 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
8939 return FD->getDescribedFunctionTemplate();
8940 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
8941 return RD->getDescribedClassTemplate();
8942
8943 llvm_unreachable("Unsupported: Getting the described template declaration"
8944 " for bad deduction diagnosis");
8945}
8946
8947/// Diagnose a failed template-argument deduction.
Richard Smith17c00b42014-11-12 01:24:00 +00008948static void DiagnoseBadDeduction(Sema &S, Decl *Templated,
8949 DeductionFailureInfo &DeductionFailure,
8950 unsigned NumArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008951 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008952 NamedDecl *ParamD;
8953 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8954 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8955 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00008956 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00008957 case Sema::TDK_Success:
8958 llvm_unreachable("TDK_success while diagnosing bad deduction");
8959
8960 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00008961 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00008962 S.Diag(Templated->getLocation(),
8963 diag::note_ovl_candidate_incomplete_deduction)
8964 << ParamD->getDeclName();
8965 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00008966 return;
8967 }
8968
John McCall42d7d192010-08-05 09:05:08 +00008969 case Sema::TDK_Underqualified: {
8970 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8971 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8972
Larisse Voufo98b20f12013-07-19 23:00:19 +00008973 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00008974
8975 // Param will have been canonicalized, but it should just be a
8976 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00008977 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00008978 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00008979 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00008980 assert(S.Context.hasSameType(Param, NonCanonParam));
8981
8982 // Arg has also been canonicalized, but there's nothing we can do
8983 // about that. It also doesn't matter as much, because it won't
8984 // have any template parameters in it (because deduction isn't
8985 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00008986 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00008987
Larisse Voufo98b20f12013-07-19 23:00:19 +00008988 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
8989 << ParamD->getDeclName() << Arg << NonCanonParam;
8990 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall42d7d192010-08-05 09:05:08 +00008991 return;
8992 }
8993
8994 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00008995 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008996 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008997 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008998 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008999 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009000 which = 1;
9001 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009002 which = 2;
9003 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009004
Larisse Voufo98b20f12013-07-19 23:00:19 +00009005 S.Diag(Templated->getLocation(),
9006 diag::note_ovl_candidate_inconsistent_deduction)
9007 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9008 << *DeductionFailure.getSecondArg();
9009 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009010 return;
9011 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00009012
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009013 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009014 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009015 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00009016 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009017 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009018 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009019 else {
9020 int index = 0;
9021 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9022 index = TTP->getIndex();
9023 else if (NonTypeTemplateParmDecl *NTTP
9024 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9025 index = NTTP->getIndex();
9026 else
9027 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00009028 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009029 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009030 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009031 }
Larisse Voufo98b20f12013-07-19 23:00:19 +00009032 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009033 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009034
Douglas Gregor02eb4832010-05-08 18:13:28 +00009035 case Sema::TDK_TooManyArguments:
9036 case Sema::TDK_TooFewArguments:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009037 DiagnoseArityMismatch(S, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00009038 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00009039
9040 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009041 S.Diag(Templated->getLocation(),
9042 diag::note_ovl_candidate_instantiation_depth);
9043 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00009044 return;
9045
9046 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00009047 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009048 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009049 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00009050 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00009051 TemplateArgString = " ";
9052 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00009053 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00009054 }
9055
Richard Smith6f8d2c62012-05-09 05:17:00 +00009056 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009057 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009058 if (PDiag && PDiag->second.getDiagID() ==
9059 diag::err_typename_nested_not_found_enable_if) {
9060 // FIXME: Use the source range of the condition, and the fully-qualified
9061 // name of the enable_if template. These are both present in PDiag.
9062 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9063 << "'enable_if'" << TemplateArgString;
9064 return;
9065 }
9066
Richard Smith9ca64612012-05-07 09:03:25 +00009067 // Format the SFINAE diagnostic into the argument string.
9068 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9069 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009070 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009071 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009072 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00009073 SFINAEArgString = ": ";
9074 R = SourceRange(PDiag->first, PDiag->first);
9075 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9076 }
9077
Larisse Voufo98b20f12013-07-19 23:00:19 +00009078 S.Diag(Templated->getLocation(),
9079 diag::note_ovl_candidate_substitution_failure)
9080 << TemplateArgString << SFINAEArgString << R;
9081 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00009082 return;
9083 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009084
Richard Smith8c6eeb92013-01-31 04:03:12 +00009085 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009086 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9087 S.Diag(Templated->getLocation(),
Richard Smith8c6eeb92013-01-31 04:03:12 +00009088 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009089 << R.Expression->getName();
Richard Smith8c6eeb92013-01-31 04:03:12 +00009090 return;
9091 }
9092
Richard Trieue3732352013-04-08 21:11:40 +00009093 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00009094 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009095 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9096 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00009097 if (FirstTA.getKind() == TemplateArgument::Template &&
9098 SecondTA.getKind() == TemplateArgument::Template) {
9099 TemplateName FirstTN = FirstTA.getAsTemplate();
9100 TemplateName SecondTN = SecondTA.getAsTemplate();
9101 if (FirstTN.getKind() == TemplateName::Template &&
9102 SecondTN.getKind() == TemplateName::Template) {
9103 if (FirstTN.getAsTemplateDecl()->getName() ==
9104 SecondTN.getAsTemplateDecl()->getName()) {
9105 // FIXME: This fixes a bad diagnostic where both templates are named
9106 // the same. This particular case is a bit difficult since:
9107 // 1) It is passed as a string to the diagnostic printer.
9108 // 2) The diagnostic printer only attempts to find a better
9109 // name for types, not decls.
9110 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009111 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +00009112 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9113 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9114 return;
9115 }
9116 }
9117 }
Faisal Vali2b391ab2013-09-26 19:54:12 +00009118 // FIXME: For generic lambda parameters, check if the function is a lambda
9119 // call operator, and if so, emit a prettier and more informative
9120 // diagnostic that mentions 'auto' and lambda in addition to
9121 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009122 S.Diag(Templated->getLocation(),
9123 diag::note_ovl_candidate_non_deduced_mismatch)
9124 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +00009125 return;
Richard Trieue3732352013-04-08 21:11:40 +00009126 }
John McCall8b9ed552010-02-01 18:53:26 +00009127 // TODO: diagnose these individually, then kill off
9128 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +00009129 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009130 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9131 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00009132 return;
9133 }
9134}
9135
Larisse Voufo98b20f12013-07-19 23:00:19 +00009136/// Diagnose a failed template-argument deduction, for function calls.
Richard Smith17c00b42014-11-12 01:24:00 +00009137static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
9138 unsigned NumArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009139 unsigned TDK = Cand->DeductionFailure.Result;
9140 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9141 if (CheckArityMismatch(S, Cand, NumArgs))
9142 return;
9143 }
9144 DiagnoseBadDeduction(S, Cand->Function, // pattern
9145 Cand->DeductionFailure, NumArgs);
9146}
9147
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009148/// CUDA: diagnose an invalid call across targets.
Richard Smith17c00b42014-11-12 01:24:00 +00009149static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009150 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9151 FunctionDecl *Callee = Cand->Function;
9152
9153 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9154 CalleeTarget = S.IdentifyCUDATarget(Callee);
9155
9156 std::string FnDesc;
9157 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
9158
9159 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009160 << (unsigned)FnKind << CalleeTarget << CallerTarget;
9161
9162 // This could be an implicit constructor for which we could not infer the
9163 // target due to a collsion. Diagnose that case.
9164 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9165 if (Meth != nullptr && Meth->isImplicit()) {
9166 CXXRecordDecl *ParentClass = Meth->getParent();
9167 Sema::CXXSpecialMember CSM;
9168
9169 switch (FnKind) {
9170 default:
9171 return;
9172 case oc_implicit_default_constructor:
9173 CSM = Sema::CXXDefaultConstructor;
9174 break;
9175 case oc_implicit_copy_constructor:
9176 CSM = Sema::CXXCopyConstructor;
9177 break;
9178 case oc_implicit_move_constructor:
9179 CSM = Sema::CXXMoveConstructor;
9180 break;
9181 case oc_implicit_copy_assignment:
9182 CSM = Sema::CXXCopyAssignment;
9183 break;
9184 case oc_implicit_move_assignment:
9185 CSM = Sema::CXXMoveAssignment;
9186 break;
9187 };
9188
9189 bool ConstRHS = false;
9190 if (Meth->getNumParams()) {
9191 if (const ReferenceType *RT =
9192 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9193 ConstRHS = RT->getPointeeType().isConstQualified();
9194 }
9195 }
9196
9197 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9198 /* ConstRHS */ ConstRHS,
9199 /* Diagnose */ true);
9200 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009201}
9202
Richard Smith17c00b42014-11-12 01:24:00 +00009203static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009204 FunctionDecl *Callee = Cand->Function;
9205 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9206
9207 S.Diag(Callee->getLocation(),
9208 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9209 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9210}
9211
John McCall8b9ed552010-02-01 18:53:26 +00009212/// Generates a 'note' diagnostic for an overload candidate. We've
9213/// already generated a primary error at the call site.
9214///
9215/// It really does need to be a single diagnostic with its caret
9216/// pointed at the candidate declaration. Yes, this creates some
9217/// major challenges of technical writing. Yes, this makes pointing
9218/// out problems with specific arguments quite awkward. It's still
9219/// better than generating twenty screens of text for every failed
9220/// overload.
9221///
9222/// It would be great to be able to express per-candidate problems
9223/// more richly for those diagnostic clients that cared, but we'd
9224/// still have to be just as careful with the default diagnostics.
Richard Smith17c00b42014-11-12 01:24:00 +00009225static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
9226 unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00009227 FunctionDecl *Fn = Cand->Function;
9228
John McCall12f97bc2010-01-08 04:41:39 +00009229 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009230 if (Cand->Viable && (Fn->isDeleted() ||
9231 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00009232 std::string FnDesc;
9233 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00009234
9235 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00009236 << FnKind << FnDesc
9237 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redl08905022011-02-05 19:23:19 +00009238 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00009239 return;
John McCall12f97bc2010-01-08 04:41:39 +00009240 }
9241
John McCalle1ac8d12010-01-13 00:25:19 +00009242 // We don't really have anything else to say about viable candidates.
9243 if (Cand->Viable) {
9244 S.NoteOverloadCandidate(Fn);
9245 return;
9246 }
John McCall0d1da222010-01-12 00:44:57 +00009247
John McCall6a61b522010-01-13 09:16:55 +00009248 switch (Cand->FailureKind) {
9249 case ovl_fail_too_many_arguments:
9250 case ovl_fail_too_few_arguments:
9251 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00009252
John McCall6a61b522010-01-13 09:16:55 +00009253 case ovl_fail_bad_deduction:
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009254 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall8b9ed552010-02-01 18:53:26 +00009255
John McCall578a1f82014-12-14 01:46:53 +00009256 case ovl_fail_illegal_constructor: {
9257 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9258 << (Fn->getPrimaryTemplate() ? 1 : 0);
9259 MaybeEmitInheritedConstructorNote(S, Fn);
9260 return;
9261 }
9262
John McCallfe796dd2010-01-23 05:17:32 +00009263 case ovl_fail_trivial_conversion:
9264 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00009265 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00009266 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009267
John McCall65eb8792010-02-25 01:37:24 +00009268 case ovl_fail_bad_conversion: {
9269 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009270 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00009271 if (Cand->Conversions[I].isBad())
9272 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009273
John McCall6a61b522010-01-13 09:16:55 +00009274 // FIXME: this currently happens when we're called from SemaInit
9275 // when user-conversion overload fails. Figure out how to handle
9276 // those conditions and diagnose them well.
9277 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009278 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009279
9280 case ovl_fail_bad_target:
9281 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009282
9283 case ovl_fail_enable_if:
9284 return DiagnoseFailedEnableIfAttr(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00009285 }
John McCalld3224162010-01-08 00:58:21 +00009286}
9287
Richard Smith17c00b42014-11-12 01:24:00 +00009288static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
John McCalld3224162010-01-08 00:58:21 +00009289 // Desugar the type of the surrogate down to a function type,
9290 // retaining as many typedefs as possible while still showing
9291 // the function type (and, therefore, its parameter types).
9292 QualType FnType = Cand->Surrogate->getConversionType();
9293 bool isLValueReference = false;
9294 bool isRValueReference = false;
9295 bool isPointer = false;
9296 if (const LValueReferenceType *FnTypeRef =
9297 FnType->getAs<LValueReferenceType>()) {
9298 FnType = FnTypeRef->getPointeeType();
9299 isLValueReference = true;
9300 } else if (const RValueReferenceType *FnTypeRef =
9301 FnType->getAs<RValueReferenceType>()) {
9302 FnType = FnTypeRef->getPointeeType();
9303 isRValueReference = true;
9304 }
9305 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9306 FnType = FnTypePtr->getPointeeType();
9307 isPointer = true;
9308 }
9309 // Desugar down to a function type.
9310 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9311 // Reconstruct the pointer/reference as appropriate.
9312 if (isPointer) FnType = S.Context.getPointerType(FnType);
9313 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9314 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9315
9316 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9317 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00009318 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00009319}
9320
Richard Smith17c00b42014-11-12 01:24:00 +00009321static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9322 SourceLocation OpLoc,
9323 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009324 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00009325 std::string TypeStr("operator");
9326 TypeStr += Opc;
9327 TypeStr += "(";
9328 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00009329 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00009330 TypeStr += ")";
9331 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9332 } else {
9333 TypeStr += ", ";
9334 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9335 TypeStr += ")";
9336 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9337 }
9338}
9339
Richard Smith17c00b42014-11-12 01:24:00 +00009340static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9341 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009342 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00009343 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9344 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00009345 if (ICS.isBad()) break; // all meaningless after first invalid
9346 if (!ICS.isAmbiguous()) continue;
9347
John McCall5c32be02010-08-24 20:38:10 +00009348 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00009349 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00009350 }
9351}
9352
Larisse Voufo98b20f12013-07-19 23:00:19 +00009353static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +00009354 if (Cand->Function)
9355 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00009356 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00009357 return Cand->Surrogate->getLocation();
9358 return SourceLocation();
9359}
9360
Larisse Voufo98b20f12013-07-19 23:00:19 +00009361static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00009362 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009363 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00009364 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009365
Douglas Gregorc5c01a62012-09-13 21:01:57 +00009366 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009367 case Sema::TDK_Incomplete:
9368 return 1;
9369
9370 case Sema::TDK_Underqualified:
9371 case Sema::TDK_Inconsistent:
9372 return 2;
9373
9374 case Sema::TDK_SubstitutionFailure:
9375 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +00009376 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009377 return 3;
9378
9379 case Sema::TDK_InstantiationDepth:
9380 case Sema::TDK_FailedOverloadResolution:
9381 return 4;
9382
9383 case Sema::TDK_InvalidExplicitArguments:
9384 return 5;
9385
9386 case Sema::TDK_TooManyArguments:
9387 case Sema::TDK_TooFewArguments:
9388 return 6;
9389 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009390 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009391}
9392
Richard Smith17c00b42014-11-12 01:24:00 +00009393namespace {
John McCallad2587a2010-01-12 00:48:53 +00009394struct CompareOverloadCandidatesForDisplay {
9395 Sema &S;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009396 size_t NumArgs;
9397
9398 CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs)
9399 : S(S), NumArgs(nArgs) {}
John McCall12f97bc2010-01-08 04:41:39 +00009400
9401 bool operator()(const OverloadCandidate *L,
9402 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00009403 // Fast-path this check.
9404 if (L == R) return false;
9405
John McCall12f97bc2010-01-08 04:41:39 +00009406 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00009407 if (L->Viable) {
9408 if (!R->Viable) return true;
9409
9410 // TODO: introduce a tri-valued comparison for overload
9411 // candidates. Would be more worthwhile if we had a sort
9412 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00009413 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9414 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00009415 } else if (R->Viable)
9416 return false;
John McCall12f97bc2010-01-08 04:41:39 +00009417
John McCall3712d9e2010-01-15 23:32:50 +00009418 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00009419
John McCall3712d9e2010-01-15 23:32:50 +00009420 // Criteria by which we can sort non-viable candidates:
9421 if (!L->Viable) {
9422 // 1. Arity mismatches come after other candidates.
9423 if (L->FailureKind == ovl_fail_too_many_arguments ||
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009424 L->FailureKind == ovl_fail_too_few_arguments) {
9425 if (R->FailureKind == ovl_fail_too_many_arguments ||
9426 R->FailureKind == ovl_fail_too_few_arguments) {
Kaelyn Takata50c4ffc2014-05-07 00:43:38 +00009427 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9428 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9429 if (LDist == RDist) {
9430 if (L->FailureKind == R->FailureKind)
9431 // Sort non-surrogates before surrogates.
9432 return !L->IsSurrogate && R->IsSurrogate;
9433 // Sort candidates requiring fewer parameters than there were
9434 // arguments given after candidates requiring more parameters
9435 // than there were arguments given.
9436 return L->FailureKind == ovl_fail_too_many_arguments;
9437 }
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009438 return LDist < RDist;
9439 }
John McCall3712d9e2010-01-15 23:32:50 +00009440 return false;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009441 }
John McCall3712d9e2010-01-15 23:32:50 +00009442 if (R->FailureKind == ovl_fail_too_many_arguments ||
9443 R->FailureKind == ovl_fail_too_few_arguments)
9444 return true;
John McCall12f97bc2010-01-08 04:41:39 +00009445
John McCallfe796dd2010-01-23 05:17:32 +00009446 // 2. Bad conversions come first and are ordered by the number
9447 // of bad conversions and quality of good conversions.
9448 if (L->FailureKind == ovl_fail_bad_conversion) {
9449 if (R->FailureKind != ovl_fail_bad_conversion)
9450 return true;
9451
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009452 // The conversion that can be fixed with a smaller number of changes,
9453 // comes first.
9454 unsigned numLFixes = L->Fix.NumConversionsFixed;
9455 unsigned numRFixes = R->Fix.NumConversionsFixed;
9456 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9457 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009458 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009459 if (numLFixes < numRFixes)
9460 return true;
9461 else
9462 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009463 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009464
John McCallfe796dd2010-01-23 05:17:32 +00009465 // If there's any ordering between the defined conversions...
9466 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00009467 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00009468
9469 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00009470 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009471 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00009472 switch (CompareImplicitConversionSequences(S,
9473 L->Conversions[I],
9474 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00009475 case ImplicitConversionSequence::Better:
9476 leftBetter++;
9477 break;
9478
9479 case ImplicitConversionSequence::Worse:
9480 leftBetter--;
9481 break;
9482
9483 case ImplicitConversionSequence::Indistinguishable:
9484 break;
9485 }
9486 }
9487 if (leftBetter > 0) return true;
9488 if (leftBetter < 0) return false;
9489
9490 } else if (R->FailureKind == ovl_fail_bad_conversion)
9491 return false;
9492
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009493 if (L->FailureKind == ovl_fail_bad_deduction) {
9494 if (R->FailureKind != ovl_fail_bad_deduction)
9495 return true;
9496
9497 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9498 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00009499 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00009500 } else if (R->FailureKind == ovl_fail_bad_deduction)
9501 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009502
John McCall3712d9e2010-01-15 23:32:50 +00009503 // TODO: others?
9504 }
9505
9506 // Sort everything else by location.
9507 SourceLocation LLoc = GetLocationForCandidate(L);
9508 SourceLocation RLoc = GetLocationForCandidate(R);
9509
9510 // Put candidates without locations (e.g. builtins) at the end.
9511 if (LLoc.isInvalid()) return false;
9512 if (RLoc.isInvalid()) return true;
9513
9514 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00009515 }
9516};
Richard Smith17c00b42014-11-12 01:24:00 +00009517}
John McCall12f97bc2010-01-08 04:41:39 +00009518
John McCallfe796dd2010-01-23 05:17:32 +00009519/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009520/// computes up to the first. Produces the FixIt set if possible.
Richard Smith17c00b42014-11-12 01:24:00 +00009521static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9522 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00009523 assert(!Cand->Viable);
9524
9525 // Don't do anything on failures other than bad conversion.
9526 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9527
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009528 // We only want the FixIts if all the arguments can be corrected.
9529 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00009530 // Use a implicit copy initialization to check conversion fixes.
9531 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009532
John McCallfe796dd2010-01-23 05:17:32 +00009533 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00009534 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009535 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00009536 while (true) {
9537 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9538 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009539 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00009540 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00009541 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009542 }
John McCallfe796dd2010-01-23 05:17:32 +00009543 }
9544
9545 if (ConvIdx == ConvCount)
9546 return;
9547
John McCall65eb8792010-02-25 01:37:24 +00009548 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9549 "remaining conversion is initialized?");
9550
Douglas Gregoradc7a702010-04-16 17:45:54 +00009551 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00009552 // operation somehow.
9553 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00009554
9555 const FunctionProtoType* Proto;
9556 unsigned ArgIdx = ConvIdx;
9557
9558 if (Cand->IsSurrogate) {
9559 QualType ConvType
9560 = Cand->Surrogate->getConversionType().getNonReferenceType();
9561 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9562 ConvType = ConvPtrType->getPointeeType();
9563 Proto = ConvType->getAs<FunctionProtoType>();
9564 ArgIdx--;
9565 } else if (Cand->Function) {
9566 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9567 if (isa<CXXMethodDecl>(Cand->Function) &&
9568 !isa<CXXConstructorDecl>(Cand->Function))
9569 ArgIdx--;
9570 } else {
9571 // Builtin binary operator with a bad first conversion.
9572 assert(ConvCount <= 3);
9573 for (; ConvIdx != ConvCount; ++ConvIdx)
9574 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00009575 = TryCopyInitialization(S, Args[ConvIdx],
9576 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009577 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00009578 /*InOverloadResolution*/ true,
9579 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00009580 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00009581 return;
9582 }
9583
9584 // Fill in the rest of the conversions.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009585 unsigned NumParams = Proto->getNumParams();
John McCallfe796dd2010-01-23 05:17:32 +00009586 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009587 if (ArgIdx < NumParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009588 Cand->Conversions[ConvIdx] = TryCopyInitialization(
9589 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
9590 /*InOverloadResolution=*/true,
9591 /*AllowObjCWritebackConversion=*/
9592 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009593 // Store the FixIt in the candidate if it exists.
9594 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00009595 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009596 }
John McCallfe796dd2010-01-23 05:17:32 +00009597 else
9598 Cand->Conversions[ConvIdx].setEllipsis();
9599 }
9600}
9601
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009602/// PrintOverloadCandidates - When overload resolution fails, prints
9603/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00009604/// set.
John McCall5c32be02010-08-24 20:38:10 +00009605void OverloadCandidateSet::NoteCandidates(Sema &S,
9606 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009607 ArrayRef<Expr *> Args,
David Blaikie1d202a62012-10-08 01:11:04 +00009608 StringRef Opc,
John McCall5c32be02010-08-24 20:38:10 +00009609 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00009610 // Sort the candidates by viability and position. Sorting directly would
9611 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009612 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00009613 if (OCD == OCD_AllCandidates) Cands.reserve(size());
9614 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00009615 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00009616 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00009617 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009618 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009619 if (Cand->Function || Cand->IsSurrogate)
9620 Cands.push_back(Cand);
9621 // Otherwise, this a non-viable builtin candidate. We do not, in general,
9622 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00009623 }
9624 }
9625
John McCallad2587a2010-01-12 00:48:53 +00009626 std::sort(Cands.begin(), Cands.end(),
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009627 CompareOverloadCandidatesForDisplay(S, Args.size()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009628
John McCall0d1da222010-01-12 00:44:57 +00009629 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00009630
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009631 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +00009632 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009633 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00009634 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9635 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00009636
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009637 // Set an arbitrary limit on the number of candidate functions we'll spam
9638 // the user with. FIXME: This limit should depend on details of the
9639 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +00009640 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009641 break;
9642 }
9643 ++CandsShown;
9644
John McCalld3224162010-01-08 00:58:21 +00009645 if (Cand->Function)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009646 NoteFunctionCandidate(S, Cand, Args.size());
John McCalld3224162010-01-08 00:58:21 +00009647 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00009648 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009649 else {
9650 assert(Cand->Viable &&
9651 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00009652 // Generally we only see ambiguities including viable builtin
9653 // operators if overload resolution got screwed up by an
9654 // ambiguous user-defined conversion.
9655 //
9656 // FIXME: It's quite possible for different conversions to see
9657 // different ambiguities, though.
9658 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00009659 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00009660 ReportedAmbiguousConversions = true;
9661 }
John McCalld3224162010-01-08 00:58:21 +00009662
John McCall0d1da222010-01-12 00:44:57 +00009663 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00009664 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00009665 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009666 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009667
9668 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00009669 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009670}
9671
Larisse Voufo98b20f12013-07-19 23:00:19 +00009672static SourceLocation
9673GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9674 return Cand->Specialization ? Cand->Specialization->getLocation()
9675 : SourceLocation();
9676}
9677
Richard Smith17c00b42014-11-12 01:24:00 +00009678namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009679struct CompareTemplateSpecCandidatesForDisplay {
9680 Sema &S;
9681 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9682
9683 bool operator()(const TemplateSpecCandidate *L,
9684 const TemplateSpecCandidate *R) {
9685 // Fast-path this check.
9686 if (L == R)
9687 return false;
9688
9689 // Assuming that both candidates are not matches...
9690
9691 // Sort by the ranking of deduction failures.
9692 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9693 return RankDeductionFailure(L->DeductionFailure) <
9694 RankDeductionFailure(R->DeductionFailure);
9695
9696 // Sort everything else by location.
9697 SourceLocation LLoc = GetLocationForCandidate(L);
9698 SourceLocation RLoc = GetLocationForCandidate(R);
9699
9700 // Put candidates without locations (e.g. builtins) at the end.
9701 if (LLoc.isInvalid())
9702 return false;
9703 if (RLoc.isInvalid())
9704 return true;
9705
9706 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9707 }
9708};
Richard Smith17c00b42014-11-12 01:24:00 +00009709}
Larisse Voufo98b20f12013-07-19 23:00:19 +00009710
9711/// Diagnose a template argument deduction failure.
9712/// We are treating these failures as overload failures due to bad
9713/// deductions.
9714void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9715 DiagnoseBadDeduction(S, Specialization, // pattern
9716 DeductionFailure, /*NumArgs=*/0);
9717}
9718
9719void TemplateSpecCandidateSet::destroyCandidates() {
9720 for (iterator i = begin(), e = end(); i != e; ++i) {
9721 i->DeductionFailure.Destroy();
9722 }
9723}
9724
9725void TemplateSpecCandidateSet::clear() {
9726 destroyCandidates();
9727 Candidates.clear();
9728}
9729
9730/// NoteCandidates - When no template specialization match is found, prints
9731/// diagnostic messages containing the non-matching specializations that form
9732/// the candidate set.
9733/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9734/// OCD == OCD_AllCandidates and Cand->Viable == false.
9735void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9736 // Sort the candidates by position (assuming no candidate is a match).
9737 // Sorting directly would be prohibitive, so we make a set of pointers
9738 // and sort those.
9739 SmallVector<TemplateSpecCandidate *, 32> Cands;
9740 Cands.reserve(size());
9741 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9742 if (Cand->Specialization)
9743 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +00009744 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +00009745 // in general, want to list every possible builtin candidate.
9746 }
9747
9748 std::sort(Cands.begin(), Cands.end(),
9749 CompareTemplateSpecCandidatesForDisplay(S));
9750
9751 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9752 // for generalization purposes (?).
9753 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9754
9755 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9756 unsigned CandsShown = 0;
9757 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9758 TemplateSpecCandidate *Cand = *I;
9759
9760 // Set an arbitrary limit on the number of candidates we'll spam
9761 // the user with. FIXME: This limit should depend on details of the
9762 // candidate list.
9763 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9764 break;
9765 ++CandsShown;
9766
9767 assert(Cand->Specialization &&
9768 "Non-matching built-in candidates are not added to Cands.");
9769 Cand->NoteDeductionFailure(S);
9770 }
9771
9772 if (I != E)
9773 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9774}
9775
Douglas Gregorb491ed32011-02-19 21:32:49 +00009776// [PossiblyAFunctionType] --> [Return]
9777// NonFunctionType --> NonFunctionType
9778// R (A) --> R(A)
9779// R (*)(A) --> R (A)
9780// R (&)(A) --> R (A)
9781// R (S::*)(A) --> R (A)
9782QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9783 QualType Ret = PossiblyAFunctionType;
9784 if (const PointerType *ToTypePtr =
9785 PossiblyAFunctionType->getAs<PointerType>())
9786 Ret = ToTypePtr->getPointeeType();
9787 else if (const ReferenceType *ToTypeRef =
9788 PossiblyAFunctionType->getAs<ReferenceType>())
9789 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009790 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00009791 PossiblyAFunctionType->getAs<MemberPointerType>())
9792 Ret = MemTypePtr->getPointeeType();
9793 Ret =
9794 Context.getCanonicalType(Ret).getUnqualifiedType();
9795 return Ret;
9796}
Douglas Gregorcd695e52008-11-10 20:40:00 +00009797
Richard Smith17c00b42014-11-12 01:24:00 +00009798namespace {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009799// A helper class to help with address of function resolution
9800// - allows us to avoid passing around all those ugly parameters
Richard Smith17c00b42014-11-12 01:24:00 +00009801class AddressOfFunctionResolver {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009802 Sema& S;
9803 Expr* SourceExpr;
9804 const QualType& TargetType;
9805 QualType TargetFunctionType; // Extracted function type from target type
9806
9807 bool Complain;
9808 //DeclAccessPair& ResultFunctionAccessPair;
9809 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009810
Douglas Gregorb491ed32011-02-19 21:32:49 +00009811 bool TargetTypeIsNonStaticMemberFunction;
9812 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +00009813 bool StaticMemberFunctionFromBoundPointer;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009814
Douglas Gregorb491ed32011-02-19 21:32:49 +00009815 OverloadExpr::FindResult OvlExprInfo;
9816 OverloadExpr *OvlExpr;
9817 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009818 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009819 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009820
Douglas Gregorb491ed32011-02-19 21:32:49 +00009821public:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009822 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9823 const QualType &TargetType, bool Complain)
9824 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9825 Complain(Complain), Context(S.getASTContext()),
9826 TargetTypeIsNonStaticMemberFunction(
9827 !!TargetType->getAs<MemberPointerType>()),
9828 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +00009829 StaticMemberFunctionFromBoundPointer(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +00009830 OvlExprInfo(OverloadExpr::find(SourceExpr)),
9831 OvlExpr(OvlExprInfo.Expression),
9832 FailedCandidates(OvlExpr->getNameLoc()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009833 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +00009834
David Majnemera4f7c7a2013-08-01 06:13:59 +00009835 if (TargetFunctionType->isFunctionType()) {
9836 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9837 if (!UME->isImplicitAccess() &&
9838 !S.ResolveSingleFunctionTemplateSpecialization(UME))
9839 StaticMemberFunctionFromBoundPointer = true;
9840 } else if (OvlExpr->hasExplicitTemplateArgs()) {
9841 DeclAccessPair dap;
9842 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9843 OvlExpr, false, &dap)) {
9844 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9845 if (!Method->isStatic()) {
9846 // If the target type is a non-function type and the function found
9847 // is a non-static member function, pretend as if that was the
9848 // target, it's the only possible type to end up with.
9849 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +00009850
David Majnemera4f7c7a2013-08-01 06:13:59 +00009851 // And skip adding the function if its not in the proper form.
9852 // We'll diagnose this due to an empty set of functions.
9853 if (!OvlExprInfo.HasFormOfMemberPointer)
9854 return;
Chandler Carruthffce2452011-03-29 08:08:18 +00009855 }
9856
David Majnemera4f7c7a2013-08-01 06:13:59 +00009857 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +00009858 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009859 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00009860 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009861
9862 if (OvlExpr->hasExplicitTemplateArgs())
9863 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00009864
Douglas Gregorb491ed32011-02-19 21:32:49 +00009865 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9866 // C++ [over.over]p4:
9867 // If more than one function is selected, [...]
9868 if (Matches.size() > 1) {
9869 if (FoundNonTemplateFunction)
9870 EliminateAllTemplateMatches();
9871 else
9872 EliminateAllExceptMostSpecializedTemplate();
9873 }
9874 }
9875 }
9876
9877private:
9878 bool isTargetTypeAFunction() const {
9879 return TargetFunctionType->isFunctionType();
9880 }
9881
9882 // [ToType] [Return]
9883
9884 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9885 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9886 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9887 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9888 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9889 }
9890
9891 // return true if any matching specializations were found
9892 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9893 const DeclAccessPair& CurAccessFunPair) {
9894 if (CXXMethodDecl *Method
9895 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9896 // Skip non-static function templates when converting to pointer, and
9897 // static when converting to member pointer.
9898 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9899 return false;
9900 }
9901 else if (TargetTypeIsNonStaticMemberFunction)
9902 return false;
9903
9904 // C++ [over.over]p2:
9905 // If the name is a function template, template argument deduction is
9906 // done (14.8.2.2), and if the argument deduction succeeds, the
9907 // resulting template argument list is used to generate a single
9908 // function template specialization, which is added to the set of
9909 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +00009910 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009911 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +00009912 if (Sema::TemplateDeductionResult Result
9913 = S.DeduceTemplateArguments(FunctionTemplate,
9914 &OvlExplicitTemplateArgs,
9915 TargetFunctionType, Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00009916 Info, /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009917 // Make a note of the failed deduction for diagnostics.
9918 FailedCandidates.addCandidate()
9919 .set(FunctionTemplate->getTemplatedDecl(),
9920 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +00009921 return false;
9922 }
9923
Douglas Gregor19a41f12013-04-17 08:45:07 +00009924 // Template argument deduction ensures that we have an exact match or
9925 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009926 // This function template specicalization works.
9927 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Douglas Gregor19a41f12013-04-17 08:45:07 +00009928 assert(S.isSameOrCompatibleFunctionType(
9929 Context.getCanonicalType(Specialization->getType()),
9930 Context.getCanonicalType(TargetFunctionType)));
Douglas Gregorb491ed32011-02-19 21:32:49 +00009931 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9932 return true;
9933 }
9934
9935 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9936 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009937 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009938 // Skip non-static functions when converting to pointer, and static
9939 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009940 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9941 return false;
9942 }
9943 else if (TargetTypeIsNonStaticMemberFunction)
9944 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009945
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009946 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009947 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009948 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009949 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl))
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009950 return false;
9951
Richard Smith2a7d4812013-05-04 07:00:32 +00009952 // If any candidate has a placeholder return type, trigger its deduction
9953 // now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00009954 if (S.getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +00009955 FunDecl->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00009956 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
9957 return false;
9958
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00009959 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009960 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9961 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00009962 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9963 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009964 Matches.push_back(std::make_pair(CurAccessFunPair,
9965 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00009966 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009967 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00009968 }
Mike Stump11289f42009-09-09 15:08:12 +00009969 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009970
9971 return false;
9972 }
9973
9974 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9975 bool Ret = false;
9976
9977 // If the overload expression doesn't have the form of a pointer to
9978 // member, don't try to convert it to a pointer-to-member type.
9979 if (IsInvalidFormOfPointerToMemberFunction())
9980 return false;
9981
9982 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9983 E = OvlExpr->decls_end();
9984 I != E; ++I) {
9985 // Look through any using declarations to find the underlying function.
9986 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9987
9988 // C++ [over.over]p3:
9989 // Non-member functions and static member functions match
9990 // targets of type "pointer-to-function" or "reference-to-function."
9991 // Nonstatic member functions match targets of
9992 // type "pointer-to-member-function."
9993 // Note that according to DR 247, the containing class does not matter.
9994 if (FunctionTemplateDecl *FunctionTemplate
9995 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9996 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9997 Ret = true;
9998 }
9999 // If we have explicit template arguments supplied, skip non-templates.
10000 else if (!OvlExpr->hasExplicitTemplateArgs() &&
10001 AddMatchingNonTemplateFunction(Fn, I.getPair()))
10002 Ret = true;
10003 }
10004 assert(Ret || Matches.empty());
10005 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010006 }
10007
Douglas Gregorb491ed32011-02-19 21:32:49 +000010008 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +000010009 // [...] and any given function template specialization F1 is
10010 // eliminated if the set contains a second function template
10011 // specialization whose function template is more specialized
10012 // than the function template of F1 according to the partial
10013 // ordering rules of 14.5.5.2.
10014
10015 // The algorithm specified above is quadratic. We instead use a
10016 // two-pass algorithm (similar to the one used to identify the
10017 // best viable function in an overload set) that identifies the
10018 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +000010019
10020 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10021 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10022 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010023
Larisse Voufo98b20f12013-07-19 23:00:19 +000010024 // TODO: It looks like FailedCandidates does not serve much purpose
10025 // here, since the no_viable diagnostic has index 0.
10026 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +000010027 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010028 SourceExpr->getLocStart(), S.PDiag(),
10029 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
10030 .second->getDeclName(),
10031 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
10032 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010033
Douglas Gregorb491ed32011-02-19 21:32:49 +000010034 if (Result != MatchesCopy.end()) {
10035 // Make it the first and only element
10036 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10037 Matches[0].second = cast<FunctionDecl>(*Result);
10038 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +000010039 }
10040 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010041
Douglas Gregorb491ed32011-02-19 21:32:49 +000010042 void EliminateAllTemplateMatches() {
10043 // [...] any function template specializations in the set are
10044 // eliminated if the set also contains a non-template function, [...]
10045 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010046 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010047 ++I;
10048 else {
10049 Matches[I] = Matches[--N];
10050 Matches.set_size(N);
10051 }
10052 }
10053 }
10054
10055public:
10056 void ComplainNoMatchesFound() const {
10057 assert(Matches.empty());
10058 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10059 << OvlExpr->getName() << TargetFunctionType
10060 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +000010061 if (FailedCandidates.empty())
10062 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
10063 else {
10064 // We have some deduction failure messages. Use them to diagnose
10065 // the function templates, and diagnose the non-template candidates
10066 // normally.
10067 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10068 IEnd = OvlExpr->decls_end();
10069 I != IEnd; ++I)
10070 if (FunctionDecl *Fun =
10071 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
10072 S.NoteOverloadCandidate(Fun, TargetFunctionType);
10073 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10074 }
10075 }
10076
Douglas Gregorb491ed32011-02-19 21:32:49 +000010077 bool IsInvalidFormOfPointerToMemberFunction() const {
10078 return TargetTypeIsNonStaticMemberFunction &&
10079 !OvlExprInfo.HasFormOfMemberPointer;
10080 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010081
Douglas Gregorb491ed32011-02-19 21:32:49 +000010082 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10083 // TODO: Should we condition this on whether any functions might
10084 // have matched, or is it more appropriate to do that in callers?
10085 // TODO: a fixit wouldn't hurt.
10086 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10087 << TargetType << OvlExpr->getSourceRange();
10088 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010089
10090 bool IsStaticMemberFunctionFromBoundPointer() const {
10091 return StaticMemberFunctionFromBoundPointer;
10092 }
10093
10094 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10095 S.Diag(OvlExpr->getLocStart(),
10096 diag::err_invalid_form_pointer_member_function)
10097 << OvlExpr->getSourceRange();
10098 }
10099
Douglas Gregorb491ed32011-02-19 21:32:49 +000010100 void ComplainOfInvalidConversion() const {
10101 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10102 << OvlExpr->getName() << TargetType;
10103 }
10104
10105 void ComplainMultipleMatchesFound() const {
10106 assert(Matches.size() > 1);
10107 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10108 << OvlExpr->getName()
10109 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +000010110 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010111 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010112
10113 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10114
Douglas Gregorb491ed32011-02-19 21:32:49 +000010115 int getNumMatches() const { return Matches.size(); }
10116
10117 FunctionDecl* getMatchingFunctionDecl() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010118 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010119 return Matches[0].second;
10120 }
10121
10122 const DeclAccessPair* getMatchingFunctionAccessPair() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010123 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010124 return &Matches[0].first;
10125 }
10126};
Richard Smith17c00b42014-11-12 01:24:00 +000010127}
10128
Douglas Gregorb491ed32011-02-19 21:32:49 +000010129/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10130/// an overloaded function (C++ [over.over]), where @p From is an
10131/// expression with overloaded function type and @p ToType is the type
10132/// we're trying to resolve to. For example:
10133///
10134/// @code
10135/// int f(double);
10136/// int f(int);
10137///
10138/// int (*pfd)(double) = f; // selects f(double)
10139/// @endcode
10140///
10141/// This routine returns the resulting FunctionDecl if it could be
10142/// resolved, and NULL otherwise. When @p Complain is true, this
10143/// routine will emit diagnostics if there is an error.
10144FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010145Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10146 QualType TargetType,
10147 bool Complain,
10148 DeclAccessPair &FoundResult,
10149 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010150 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010151
10152 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10153 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010154 int NumMatches = Resolver.getNumMatches();
Craig Topperc3ec1492014-05-26 06:22:03 +000010155 FunctionDecl *Fn = nullptr;
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010156 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010157 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10158 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10159 else
10160 Resolver.ComplainNoMatchesFound();
10161 }
10162 else if (NumMatches > 1 && Complain)
10163 Resolver.ComplainMultipleMatchesFound();
10164 else if (NumMatches == 1) {
10165 Fn = Resolver.getMatchingFunctionDecl();
10166 assert(Fn);
10167 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +000010168 if (Complain) {
10169 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10170 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10171 else
10172 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10173 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +000010174 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010175
10176 if (pHadMultipleCandidates)
10177 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010178 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010179}
10180
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010181/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010182/// resolve that overloaded function expression down to a single function.
10183///
10184/// This routine can only resolve template-ids that refer to a single function
10185/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010186/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010187/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +000010188///
10189/// If no template-ids are found, no diagnostics are emitted and NULL is
10190/// returned.
John McCall0009fcc2011-04-26 20:42:42 +000010191FunctionDecl *
10192Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10193 bool Complain,
10194 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010195 // C++ [over.over]p1:
10196 // [...] [Note: any redundant set of parentheses surrounding the
10197 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010198 // C++ [over.over]p1:
10199 // [...] The overloaded function name can be preceded by the &
10200 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010201
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010202 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +000010203 if (!ovl->hasExplicitTemplateArgs())
Craig Topperc3ec1492014-05-26 06:22:03 +000010204 return nullptr;
John McCall1acbbb52010-02-02 06:20:04 +000010205
10206 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +000010207 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010208 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010209
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010210 // Look through all of the overloaded functions, searching for one
10211 // whose type matches exactly.
Craig Topperc3ec1492014-05-26 06:22:03 +000010212 FunctionDecl *Matched = nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010213 for (UnresolvedSetIterator I = ovl->decls_begin(),
10214 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010215 // C++0x [temp.arg.explicit]p3:
10216 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010217 // where deduction is not done, if a template argument list is
10218 // specified and it, along with any default template arguments,
10219 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010220 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +000010221 FunctionTemplateDecl *FunctionTemplate
10222 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010223
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010224 // C++ [over.over]p2:
10225 // If the name is a function template, template argument deduction is
10226 // done (14.8.2.2), and if the argument deduction succeeds, the
10227 // resulting template argument list is used to generate a single
10228 // function template specialization, which is added to the set of
10229 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010230 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010231 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010232 if (TemplateDeductionResult Result
10233 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000010234 Specialization, Info,
10235 /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010236 // Make a note of the failed deduction for diagnostics.
10237 // TODO: Actually use the failed-deduction info?
10238 FailedCandidates.addCandidate()
10239 .set(FunctionTemplate->getTemplatedDecl(),
10240 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010241 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010242 }
10243
John McCall0009fcc2011-04-26 20:42:42 +000010244 assert(Specialization && "no specialization and no error?");
10245
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010246 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010247 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010248 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000010249 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10250 << ovl->getName();
10251 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010252 }
Craig Topperc3ec1492014-05-26 06:22:03 +000010253 return nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010254 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010255
John McCall0009fcc2011-04-26 20:42:42 +000010256 Matched = Specialization;
10257 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010258 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010259
Aaron Ballmandd69ef32014-08-19 15:55:55 +000010260 if (Matched && getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +000010261 Matched->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +000010262 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
Craig Topperc3ec1492014-05-26 06:22:03 +000010263 return nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +000010264
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010265 return Matched;
10266}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010267
Douglas Gregor1beec452011-03-12 01:48:56 +000010268
10269
10270
John McCall50a2c2c2011-10-11 23:14:30 +000010271// Resolve and fix an overloaded expression that can be resolved
10272// because it identifies a single function template specialization.
10273//
Douglas Gregor1beec452011-03-12 01:48:56 +000010274// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000010275//
10276// Return true if it was logically possible to so resolve the
10277// expression, regardless of whether or not it succeeded. Always
10278// returns true if 'complain' is set.
10279bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10280 ExprResult &SrcExpr, bool doFunctionPointerConverion,
10281 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +000010282 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000010283 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000010284 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000010285
John McCall50a2c2c2011-10-11 23:14:30 +000010286 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000010287
John McCall0009fcc2011-04-26 20:42:42 +000010288 DeclAccessPair found;
10289 ExprResult SingleFunctionExpression;
10290 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10291 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010292 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000010293 SrcExpr = ExprError();
10294 return true;
10295 }
John McCall0009fcc2011-04-26 20:42:42 +000010296
10297 // It is only correct to resolve to an instance method if we're
10298 // resolving a form that's permitted to be a pointer to member.
10299 // Otherwise we'll end up making a bound member expression, which
10300 // is illegal in all the contexts we resolve like this.
10301 if (!ovl.HasFormOfMemberPointer &&
10302 isa<CXXMethodDecl>(fn) &&
10303 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000010304 if (!complain) return false;
10305
10306 Diag(ovl.Expression->getExprLoc(),
10307 diag::err_bound_member_function)
10308 << 0 << ovl.Expression->getSourceRange();
10309
10310 // TODO: I believe we only end up here if there's a mix of
10311 // static and non-static candidates (otherwise the expression
10312 // would have 'bound member' type, not 'overload' type).
10313 // Ideally we would note which candidate was chosen and why
10314 // the static candidates were rejected.
10315 SrcExpr = ExprError();
10316 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010317 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010318
Sylvestre Ledrua5202662012-07-31 06:56:50 +000010319 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000010320 SingleFunctionExpression =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010321 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall0009fcc2011-04-26 20:42:42 +000010322
10323 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000010324 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000010325 SingleFunctionExpression =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010326 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall50a2c2c2011-10-11 23:14:30 +000010327 if (SingleFunctionExpression.isInvalid()) {
10328 SrcExpr = ExprError();
10329 return true;
10330 }
10331 }
John McCall0009fcc2011-04-26 20:42:42 +000010332 }
10333
10334 if (!SingleFunctionExpression.isUsable()) {
10335 if (complain) {
10336 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10337 << ovl.Expression->getName()
10338 << DestTypeForComplaining
10339 << OpRangeForComplaining
10340 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000010341 NoteAllOverloadCandidates(SrcExpr.get());
10342
10343 SrcExpr = ExprError();
10344 return true;
10345 }
10346
10347 return false;
John McCall0009fcc2011-04-26 20:42:42 +000010348 }
10349
John McCall50a2c2c2011-10-11 23:14:30 +000010350 SrcExpr = SingleFunctionExpression;
10351 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010352}
10353
Douglas Gregorcabea402009-09-22 15:41:20 +000010354/// \brief Add a single candidate to the overload set.
10355static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000010356 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000010357 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010358 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010359 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000010360 bool PartialOverloading,
10361 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000010362 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000010363 if (isa<UsingShadowDecl>(Callee))
10364 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10365
Douglas Gregorcabea402009-09-22 15:41:20 +000010366 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000010367 if (ExplicitTemplateArgs) {
10368 assert(!KnownValid && "Explicit template arguments?");
10369 return;
10370 }
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010371 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
10372 /*SuppressUsedConversions=*/false,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010373 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010374 return;
John McCalld14a8642009-11-21 08:51:07 +000010375 }
10376
10377 if (FunctionTemplateDecl *FuncTemplate
10378 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000010379 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010380 ExplicitTemplateArgs, Args, CandidateSet,
10381 /*SuppressUsedConversions=*/false,
10382 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +000010383 return;
10384 }
10385
Richard Smith95ce4f62011-06-26 22:19:54 +000010386 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000010387}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010388
Douglas Gregorcabea402009-09-22 15:41:20 +000010389/// \brief Add the overload candidates named by callee and/or found by argument
10390/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000010391void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010392 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010393 OverloadCandidateSet &CandidateSet,
10394 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000010395
10396#ifndef NDEBUG
10397 // Verify that ArgumentDependentLookup is consistent with the rules
10398 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000010399 //
Douglas Gregorcabea402009-09-22 15:41:20 +000010400 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10401 // and let Y be the lookup set produced by argument dependent
10402 // lookup (defined as follows). If X contains
10403 //
10404 // -- a declaration of a class member, or
10405 //
10406 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000010407 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000010408 //
10409 // -- a declaration that is neither a function or a function
10410 // template
10411 //
10412 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000010413
John McCall57500772009-12-16 12:17:52 +000010414 if (ULE->requiresADL()) {
10415 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10416 E = ULE->decls_end(); I != E; ++I) {
10417 assert(!(*I)->getDeclContext()->isRecord());
10418 assert(isa<UsingShadowDecl>(*I) ||
10419 !(*I)->getDeclContext()->isFunctionOrMethod());
10420 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000010421 }
10422 }
10423#endif
10424
John McCall57500772009-12-16 12:17:52 +000010425 // It would be nice to avoid this copy.
10426 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000010427 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000010428 if (ULE->hasExplicitTemplateArgs()) {
10429 ULE->copyTemplateArgumentsInto(TABuffer);
10430 ExplicitTemplateArgs = &TABuffer;
10431 }
10432
10433 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10434 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010435 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10436 CandidateSet, PartialOverloading,
10437 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000010438
John McCall57500772009-12-16 12:17:52 +000010439 if (ULE->requiresADL())
Richard Smith100b24a2014-04-17 01:52:14 +000010440 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010441 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000010442 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010443}
John McCalld681c392009-12-16 08:11:27 +000010444
Richard Smith0603bbb2013-06-12 22:56:54 +000010445/// Determine whether a declaration with the specified name could be moved into
10446/// a different namespace.
10447static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10448 switch (Name.getCXXOverloadedOperator()) {
10449 case OO_New: case OO_Array_New:
10450 case OO_Delete: case OO_Array_Delete:
10451 return false;
10452
10453 default:
10454 return true;
10455 }
10456}
10457
Richard Smith998a5912011-06-05 22:42:48 +000010458/// Attempt to recover from an ill-formed use of a non-dependent name in a
10459/// template, where the non-dependent name was declared after the template
10460/// was defined. This is common in code written for a compilers which do not
10461/// correctly implement two-stage name lookup.
10462///
10463/// Returns true if a viable candidate was found and a diagnostic was issued.
10464static bool
10465DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10466 const CXXScopeSpec &SS, LookupResult &R,
Richard Smith100b24a2014-04-17 01:52:14 +000010467 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smith998a5912011-06-05 22:42:48 +000010468 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010469 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000010470 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10471 return false;
10472
10473 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000010474 if (DC->isTransparentContext())
10475 continue;
10476
Richard Smith998a5912011-06-05 22:42:48 +000010477 SemaRef.LookupQualifiedName(R, DC);
10478
10479 if (!R.empty()) {
10480 R.suppressDiagnostics();
10481
10482 if (isa<CXXRecordDecl>(DC)) {
10483 // Don't diagnose names we find in classes; we get much better
10484 // diagnostics for these from DiagnoseEmptyLookup.
10485 R.clear();
10486 return false;
10487 }
10488
Richard Smith100b24a2014-04-17 01:52:14 +000010489 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smith998a5912011-06-05 22:42:48 +000010490 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10491 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010492 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000010493 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000010494
10495 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000010496 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000010497 // No viable functions. Don't bother the user with notes for functions
10498 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000010499 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000010500 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000010501 }
Richard Smith998a5912011-06-05 22:42:48 +000010502
10503 // Find the namespaces where ADL would have looked, and suggest
10504 // declaring the function there instead.
10505 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10506 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000010507 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000010508 AssociatedNamespaces,
10509 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000010510 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000010511 if (canBeDeclaredInNamespace(R.getLookupName())) {
10512 DeclContext *Std = SemaRef.getStdNamespace();
10513 for (Sema::AssociatedNamespaceSet::iterator
10514 it = AssociatedNamespaces.begin(),
10515 end = AssociatedNamespaces.end(); it != end; ++it) {
10516 // Never suggest declaring a function within namespace 'std'.
10517 if (Std && Std->Encloses(*it))
10518 continue;
Richard Smith21bae432012-12-22 02:46:14 +000010519
Richard Smith0603bbb2013-06-12 22:56:54 +000010520 // Never suggest declaring a function within a namespace with a
10521 // reserved name, like __gnu_cxx.
10522 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10523 if (NS &&
10524 NS->getQualifiedNameAsString().find("__") != std::string::npos)
10525 continue;
10526
10527 SuggestedNamespaces.insert(*it);
10528 }
Richard Smith998a5912011-06-05 22:42:48 +000010529 }
10530
10531 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10532 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000010533 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000010534 SemaRef.Diag(Best->Function->getLocation(),
10535 diag::note_not_found_by_two_phase_lookup)
10536 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000010537 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000010538 SemaRef.Diag(Best->Function->getLocation(),
10539 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000010540 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000010541 } else {
10542 // FIXME: It would be useful to list the associated namespaces here,
10543 // but the diagnostics infrastructure doesn't provide a way to produce
10544 // a localized representation of a list of items.
10545 SemaRef.Diag(Best->Function->getLocation(),
10546 diag::note_not_found_by_two_phase_lookup)
10547 << R.getLookupName() << 2;
10548 }
10549
10550 // Try to recover by calling this function.
10551 return true;
10552 }
10553
10554 R.clear();
10555 }
10556
10557 return false;
10558}
10559
10560/// Attempt to recover from ill-formed use of a non-dependent operator in a
10561/// template, where the non-dependent operator was declared after the template
10562/// was defined.
10563///
10564/// Returns true if a viable candidate was found and a diagnostic was issued.
10565static bool
10566DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10567 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010568 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000010569 DeclarationName OpName =
10570 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10571 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10572 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Richard Smith100b24a2014-04-17 01:52:14 +000010573 OverloadCandidateSet::CSK_Operator,
Craig Topperc3ec1492014-05-26 06:22:03 +000010574 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smith998a5912011-06-05 22:42:48 +000010575}
10576
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010577namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000010578class BuildRecoveryCallExprRAII {
10579 Sema &SemaRef;
10580public:
10581 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10582 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10583 SemaRef.IsBuildingRecoveryCallExpr = true;
10584 }
10585
10586 ~BuildRecoveryCallExprRAII() {
10587 SemaRef.IsBuildingRecoveryCallExpr = false;
10588 }
10589};
10590
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010591}
10592
Kaelyn Takata89c881b2014-10-27 18:07:29 +000010593static std::unique_ptr<CorrectionCandidateCallback>
10594MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
10595 bool HasTemplateArgs, bool AllowTypoCorrection) {
10596 if (!AllowTypoCorrection)
10597 return llvm::make_unique<NoTypoCorrectionCCC>();
10598 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
10599 HasTemplateArgs, ME);
10600}
10601
John McCalld681c392009-12-16 08:11:27 +000010602/// Attempts to recover from a call where no functions were found.
10603///
10604/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000010605static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000010606BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000010607 UnresolvedLookupExpr *ULE,
10608 SourceLocation LParenLoc,
Craig Toppere3d2ecbe2014-06-28 23:22:33 +000010609 MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000010610 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010611 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000010612 // Do not try to recover if it is already building a recovery call.
10613 // This stops infinite loops for template instantiations like
10614 //
10615 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10616 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10617 //
10618 if (SemaRef.IsBuildingRecoveryCallExpr)
10619 return ExprError();
10620 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000010621
10622 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000010623 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000010624 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000010625
John McCall57500772009-12-16 12:17:52 +000010626 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000010627 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000010628 if (ULE->hasExplicitTemplateArgs()) {
10629 ULE->copyTemplateArgumentsInto(TABuffer);
10630 ExplicitTemplateArgs = &TABuffer;
10631 }
10632
John McCalld681c392009-12-16 08:11:27 +000010633 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10634 Sema::LookupOrdinaryName);
Richard Smith998a5912011-06-05 22:42:48 +000010635 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Richard Smith100b24a2014-04-17 01:52:14 +000010636 OverloadCandidateSet::CSK_Normal,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010637 ExplicitTemplateArgs, Args) &&
Richard Smith998a5912011-06-05 22:42:48 +000010638 (!EmptyLookup ||
Kaelyn Takata89c881b2014-10-27 18:07:29 +000010639 SemaRef.DiagnoseEmptyLookup(
10640 S, SS, R,
10641 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
10642 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
10643 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000010644 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000010645
John McCall57500772009-12-16 12:17:52 +000010646 assert(!R.empty() && "lookup results empty despite recovery");
10647
10648 // Build an implicit member call if appropriate. Just drop the
10649 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000010650 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000010651 if ((*R.begin())->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +000010652 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
10653 R, ExplicitTemplateArgs);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000010654 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000010655 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000010656 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000010657 else
10658 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10659
10660 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000010661 return ExprError();
John McCall57500772009-12-16 12:17:52 +000010662
10663 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000010664 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000010665 // end up here.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010666 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010667 MultiExprArg(Args.data(), Args.size()),
10668 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000010669}
Douglas Gregor4038cf42010-06-08 17:35:15 +000010670
Sam Panzer0f384432012-08-21 00:52:01 +000010671/// \brief Constructs and populates an OverloadedCandidateSet from
10672/// the given function.
10673/// \returns true when an the ExprResult output parameter has been set.
10674bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10675 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010676 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010677 SourceLocation RParenLoc,
10678 OverloadCandidateSet *CandidateSet,
10679 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000010680#ifndef NDEBUG
10681 if (ULE->requiresADL()) {
10682 // To do ADL, we must have found an unqualified name.
10683 assert(!ULE->getQualifier() && "qualified name with ADL");
10684
10685 // We don't perform ADL for implicit declarations of builtins.
10686 // Verify that this was correctly set up.
10687 FunctionDecl *F;
10688 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10689 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10690 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000010691 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010692
John McCall57500772009-12-16 12:17:52 +000010693 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010694 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000010695 }
John McCall57500772009-12-16 12:17:52 +000010696#endif
10697
John McCall4124c492011-10-17 18:40:02 +000010698 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010699 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000010700 *Result = ExprError();
10701 return true;
10702 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000010703
John McCall57500772009-12-16 12:17:52 +000010704 // Add the functions denoted by the callee to the set of candidate
10705 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010706 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000010707
10708 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +000010709 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
10710 // out if it fails.
Sam Panzer0f384432012-08-21 00:52:01 +000010711 if (CandidateSet->empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010712 // In Microsoft mode, if we are inside a template class member function then
10713 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +000010714 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010715 // classes.
Alp Tokerbfa39342014-01-14 12:51:41 +000010716 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
Francois Pichetde232cb2011-11-25 01:10:54 +000010717 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010718 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args,
Benjamin Kramerc215e762012-08-24 11:54:20 +000010719 Context.DependentTy, VK_RValue,
10720 RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010721 CE->setTypeDependent(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010722 *Result = CE;
Sam Panzer0f384432012-08-21 00:52:01 +000010723 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010724 }
Sam Panzer0f384432012-08-21 00:52:01 +000010725 return false;
Francois Pichetbcf64712011-09-07 00:14:57 +000010726 }
John McCalld681c392009-12-16 08:11:27 +000010727
John McCall4124c492011-10-17 18:40:02 +000010728 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000010729 return false;
10730}
John McCall4124c492011-10-17 18:40:02 +000010731
Sam Panzer0f384432012-08-21 00:52:01 +000010732/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10733/// the completed call expression. If overload resolution fails, emits
10734/// diagnostics and returns ExprError()
10735static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10736 UnresolvedLookupExpr *ULE,
10737 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010738 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010739 SourceLocation RParenLoc,
10740 Expr *ExecConfig,
10741 OverloadCandidateSet *CandidateSet,
10742 OverloadCandidateSet::iterator *Best,
10743 OverloadingResult OverloadResult,
10744 bool AllowTypoCorrection) {
10745 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010746 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010747 RParenLoc, /*EmptyLookup=*/true,
10748 AllowTypoCorrection);
10749
10750 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000010751 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000010752 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000010753 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000010754 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10755 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000010756 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010757 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10758 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000010759 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010760
Richard Smith998a5912011-06-05 22:42:48 +000010761 case OR_No_Viable_Function: {
10762 // Try to recover by looking for viable functions which the user might
10763 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000010764 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010765 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010766 /*EmptyLookup=*/false,
10767 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000010768 if (!Recovery.isInvalid())
10769 return Recovery;
10770
Sam Panzer0f384432012-08-21 00:52:01 +000010771 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010772 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +000010773 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010774 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010775 break;
Richard Smith998a5912011-06-05 22:42:48 +000010776 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010777
10778 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000010779 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000010780 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010781 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010782 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000010783
Sam Panzer0f384432012-08-21 00:52:01 +000010784 case OR_Deleted: {
10785 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10786 << (*Best)->Function->isDeleted()
10787 << ULE->getName()
10788 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10789 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010790 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000010791
Sam Panzer0f384432012-08-21 00:52:01 +000010792 // We emitted an error for the unvailable/deleted function call but keep
10793 // the call in the AST.
10794 FunctionDecl *FDecl = (*Best)->Function;
10795 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010796 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10797 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000010798 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010799 }
10800
Douglas Gregorb412e172010-07-25 18:17:45 +000010801 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000010802 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010803}
10804
Sam Panzer0f384432012-08-21 00:52:01 +000010805/// BuildOverloadedCallExpr - Given the call expression that calls Fn
10806/// (which eventually refers to the declaration Func) and the call
10807/// arguments Args/NumArgs, attempt to resolve the function call down
10808/// to a specific function. If overload resolution succeeds, returns
10809/// the call expression produced by overload resolution.
10810/// Otherwise, emits diagnostics and returns ExprError.
10811ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10812 UnresolvedLookupExpr *ULE,
10813 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010814 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010815 SourceLocation RParenLoc,
10816 Expr *ExecConfig,
10817 bool AllowTypoCorrection) {
Richard Smith100b24a2014-04-17 01:52:14 +000010818 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
10819 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000010820 ExprResult result;
10821
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010822 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10823 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000010824 return result;
10825
10826 OverloadCandidateSet::iterator Best;
10827 OverloadingResult OverloadResult =
10828 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10829
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010830 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010831 RParenLoc, ExecConfig, &CandidateSet,
10832 &Best, OverloadResult,
10833 AllowTypoCorrection);
10834}
10835
John McCall4c4c1df2010-01-26 03:27:55 +000010836static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000010837 return Functions.size() > 1 ||
10838 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10839}
10840
Douglas Gregor084d8552009-03-13 23:49:33 +000010841/// \brief Create a unary operation that may resolve to an overloaded
10842/// operator.
10843///
10844/// \param OpLoc The location of the operator itself (e.g., '*').
10845///
10846/// \param OpcIn The UnaryOperator::Opcode that describes this
10847/// operator.
10848///
James Dennett18348b62012-06-22 08:52:37 +000010849/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000010850/// considered by overload resolution. The caller needs to build this
10851/// set based on the context using, e.g.,
10852/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10853/// set should not contain any member functions; those will be added
10854/// by CreateOverloadedUnaryOp().
10855///
James Dennett91738ff2012-06-22 10:32:46 +000010856/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000010857ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +000010858Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10859 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +000010860 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010861 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +000010862
10863 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10864 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10865 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010866 // TODO: provide better source location info.
10867 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000010868
John McCall4124c492011-10-17 18:40:02 +000010869 if (checkPlaceholderForOverload(*this, Input))
10870 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010871
Craig Topperc3ec1492014-05-26 06:22:03 +000010872 Expr *Args[2] = { Input, nullptr };
Douglas Gregor084d8552009-03-13 23:49:33 +000010873 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000010874
Douglas Gregor084d8552009-03-13 23:49:33 +000010875 // For post-increment and post-decrement, add the implicit '0' as
10876 // the second argument, so that we know this is a post-increment or
10877 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000010878 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010879 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000010880 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10881 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000010882 NumArgs = 2;
10883 }
10884
Richard Smithe54c3072013-05-05 15:51:06 +000010885 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10886
Douglas Gregor084d8552009-03-13 23:49:33 +000010887 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000010888 if (Fns.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010889 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
10890 VK_RValue, OK_Ordinary, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010891
Craig Topperc3ec1492014-05-26 06:22:03 +000010892 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000010893 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000010894 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000010895 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010896 /*ADL*/ true, IsOverloaded(Fns),
10897 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010898 return new (Context)
10899 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
10900 VK_RValue, OpLoc, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000010901 }
10902
10903 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000010904 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor084d8552009-03-13 23:49:33 +000010905
10906 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010907 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010908
10909 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000010910 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010911
John McCall4c4c1df2010-01-26 03:27:55 +000010912 // Add candidates from ADL.
Richard Smith100b24a2014-04-17 01:52:14 +000010913 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
Craig Topperc3ec1492014-05-26 06:22:03 +000010914 /*ExplicitTemplateArgs*/nullptr,
10915 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000010916
Douglas Gregor084d8552009-03-13 23:49:33 +000010917 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000010918 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010919
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010920 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10921
Douglas Gregor084d8552009-03-13 23:49:33 +000010922 // Perform overload resolution.
10923 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010924 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010925 case OR_Success: {
10926 // We found a built-in operator or an overloaded operator.
10927 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000010928
Douglas Gregor084d8552009-03-13 23:49:33 +000010929 if (FnDecl) {
10930 // We matched an overloaded operator. Build a call to that
10931 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000010932
Douglas Gregor084d8552009-03-13 23:49:33 +000010933 // Convert the arguments.
10934 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010935 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000010936
John Wiegley01296292011-04-08 18:41:53 +000010937 ExprResult InputRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000010938 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000010939 Best->FoundDecl, Method);
10940 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000010941 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010942 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000010943 } else {
10944 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000010945 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000010946 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010947 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000010948 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010949 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000010950 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000010951 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000010952 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010953 Input = InputInit.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000010954 }
10955
Douglas Gregor084d8552009-03-13 23:49:33 +000010956 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000010957 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010958 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010959 if (FnExpr.isInvalid())
10960 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000010961
Richard Smithc1564702013-11-15 02:58:23 +000010962 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000010963 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000010964 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10965 ResultTy = ResultTy.getNonLValueExprType(Context);
10966
Eli Friedman030eee42009-11-18 03:58:17 +000010967 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000010968 CallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010969 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Lang Hames5de91cc2012-10-02 04:45:10 +000010970 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000010971
Alp Toker314cc812014-01-25 16:55:45 +000010972 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000010973 return ExprError();
10974
John McCallb268a282010-08-23 23:25:46 +000010975 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000010976 } else {
10977 // We matched a built-in operator. Convert the arguments, then
10978 // break out so that we will build the appropriate built-in
10979 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010980 ExprResult InputRes =
10981 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10982 Best->Conversions[0], AA_Passing);
10983 if (InputRes.isInvalid())
10984 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010985 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000010986 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000010987 }
John Wiegley01296292011-04-08 18:41:53 +000010988 }
10989
10990 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000010991 // This is an erroneous use of an operator which can be overloaded by
10992 // a non-member function. Check for non-member operators which were
10993 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000010994 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000010995 // FIXME: Recover by calling the found function.
10996 return ExprError();
10997
John Wiegley01296292011-04-08 18:41:53 +000010998 // No viable function; fall through to handling this as a
10999 // built-in operator, which will produce an error message for us.
11000 break;
11001
11002 case OR_Ambiguous:
11003 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11004 << UnaryOperator::getOpcodeStr(Opc)
11005 << Input->getType()
11006 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011007 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000011008 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11009 return ExprError();
11010
11011 case OR_Deleted:
11012 Diag(OpLoc, diag::err_ovl_deleted_oper)
11013 << Best->Function->isDeleted()
11014 << UnaryOperator::getOpcodeStr(Opc)
11015 << getDeletedOrUnavailableSuffix(Best->Function)
11016 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011017 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011018 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011019 return ExprError();
11020 }
Douglas Gregor084d8552009-03-13 23:49:33 +000011021
11022 // Either we found no viable overloaded operator or we matched a
11023 // built-in operator. In either case, fall through to trying to
11024 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000011025 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000011026}
11027
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011028/// \brief Create a binary operation that may resolve to an overloaded
11029/// operator.
11030///
11031/// \param OpLoc The location of the operator itself (e.g., '+').
11032///
11033/// \param OpcIn The BinaryOperator::Opcode that describes this
11034/// operator.
11035///
James Dennett18348b62012-06-22 08:52:37 +000011036/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011037/// considered by overload resolution. The caller needs to build this
11038/// set based on the context using, e.g.,
11039/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11040/// set should not contain any member functions; those will be added
11041/// by CreateOverloadedBinOp().
11042///
11043/// \param LHS Left-hand argument.
11044/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000011045ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011046Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +000011047 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +000011048 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011049 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011050 Expr *Args[2] = { LHS, RHS };
Craig Topperc3ec1492014-05-26 06:22:03 +000011051 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011052
11053 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
11054 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11055 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11056
11057 // If either side is type-dependent, create an appropriate dependent
11058 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000011059 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000011060 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011061 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000011062 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000011063 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011064 return new (Context) BinaryOperator(
11065 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11066 OpLoc, FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011067
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011068 return new (Context) CompoundAssignOperator(
11069 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11070 Context.DependentTy, Context.DependentTy, OpLoc,
11071 FPFeatures.fp_contract);
Douglas Gregor5287f092009-11-05 00:51:44 +000011072 }
John McCall4c4c1df2010-01-26 03:27:55 +000011073
11074 // FIXME: save results of ADL from here?
Craig Topperc3ec1492014-05-26 06:22:03 +000011075 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011076 // TODO: provide better source location info in DNLoc component.
11077 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000011078 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000011079 = UnresolvedLookupExpr::Create(Context, NamingClass,
11080 NestedNameSpecifierLoc(), OpNameInfo,
11081 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011082 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011083 return new (Context)
11084 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11085 VK_RValue, OpLoc, FPFeatures.fp_contract);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011086 }
11087
John McCall4124c492011-10-17 18:40:02 +000011088 // Always do placeholder-like conversions on the RHS.
11089 if (checkPlaceholderForOverload(*this, Args[1]))
11090 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011091
John McCall526ab472011-10-25 17:37:35 +000011092 // Do placeholder-like conversion on the LHS; note that we should
11093 // not get here with a PseudoObject LHS.
11094 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000011095 if (checkPlaceholderForOverload(*this, Args[0]))
11096 return ExprError();
11097
Sebastian Redl6a96bf72009-11-18 23:10:33 +000011098 // If this is the assignment operator, we only perform overload resolution
11099 // if the left-hand side is a class or enumeration type. This is actually
11100 // a hack. The standard requires that we do overload resolution between the
11101 // various built-in candidates, but as DR507 points out, this can lead to
11102 // problems. So we do it this way, which pretty much follows what GCC does.
11103 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000011104 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000011105 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011106
John McCalle26a8722010-12-04 08:14:53 +000011107 // If this is the .* operator, which is not overloadable, just
11108 // create a built-in binary operator.
11109 if (Opc == BO_PtrMemD)
11110 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11111
Douglas Gregor084d8552009-03-13 23:49:33 +000011112 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011113 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011114
11115 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011116 AddFunctionCandidates(Fns, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011117
11118 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011119 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011120
Richard Smith0daabd72014-09-23 20:31:39 +000011121 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11122 // performed for an assignment operator (nor for operator[] nor operator->,
11123 // which don't get here).
11124 if (Opc != BO_Assign)
11125 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11126 /*ExplicitTemplateArgs*/ nullptr,
11127 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011128
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011129 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011130 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011131
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011132 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11133
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011134 // Perform overload resolution.
11135 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011136 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000011137 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011138 // We found a built-in operator or an overloaded operator.
11139 FunctionDecl *FnDecl = Best->Function;
11140
11141 if (FnDecl) {
11142 // We matched an overloaded operator. Build a call to that
11143 // operator.
11144
11145 // Convert the arguments.
11146 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000011147 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000011148 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011149
Chandler Carruth8e543b32010-12-12 08:17:55 +000011150 ExprResult Arg1 =
11151 PerformCopyInitialization(
11152 InitializedEntity::InitializeParameter(Context,
11153 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011154 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011155 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011156 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011157
John Wiegley01296292011-04-08 18:41:53 +000011158 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011159 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011160 Best->FoundDecl, Method);
11161 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011162 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011163 Args[0] = Arg0.getAs<Expr>();
11164 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011165 } else {
11166 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000011167 ExprResult Arg0 = PerformCopyInitialization(
11168 InitializedEntity::InitializeParameter(Context,
11169 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011170 SourceLocation(), Args[0]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011171 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011172 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011173
Chandler Carruth8e543b32010-12-12 08:17:55 +000011174 ExprResult Arg1 =
11175 PerformCopyInitialization(
11176 InitializedEntity::InitializeParameter(Context,
11177 FnDecl->getParamDecl(1)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011178 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011179 if (Arg1.isInvalid())
11180 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011181 Args[0] = LHS = Arg0.getAs<Expr>();
11182 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011183 }
11184
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011185 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011186 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011187 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011188 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011189 if (FnExpr.isInvalid())
11190 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011191
Richard Smithc1564702013-11-15 02:58:23 +000011192 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011193 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011194 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11195 ResultTy = ResultTy.getNonLValueExprType(Context);
11196
John McCallb268a282010-08-23 23:25:46 +000011197 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011198 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000011199 Args, ResultTy, VK, OpLoc,
11200 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011201
Alp Toker314cc812014-01-25 16:55:45 +000011202 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011203 FnDecl))
11204 return ExprError();
11205
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011206 ArrayRef<const Expr *> ArgsArray(Args, 2);
11207 // Cut off the implicit 'this'.
11208 if (isa<CXXMethodDecl>(FnDecl))
11209 ArgsArray = ArgsArray.slice(1);
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011210
11211 // Check for a self move.
11212 if (Op == OO_Equal)
11213 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11214
11215 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011216 TheCall->getSourceRange(), VariadicDoesNotApply);
11217
John McCallb268a282010-08-23 23:25:46 +000011218 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011219 } else {
11220 // We matched a built-in operator. Convert the arguments, then
11221 // break out so that we will build the appropriate built-in
11222 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011223 ExprResult ArgsRes0 =
11224 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11225 Best->Conversions[0], AA_Passing);
11226 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011227 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011228 Args[0] = ArgsRes0.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011229
John Wiegley01296292011-04-08 18:41:53 +000011230 ExprResult ArgsRes1 =
11231 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11232 Best->Conversions[1], AA_Passing);
11233 if (ArgsRes1.isInvalid())
11234 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011235 Args[1] = ArgsRes1.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011236 break;
11237 }
11238 }
11239
Douglas Gregor66950a32009-09-30 21:46:01 +000011240 case OR_No_Viable_Function: {
11241 // C++ [over.match.oper]p9:
11242 // If the operator is the operator , [...] and there are no
11243 // viable functions, then the operator is assumed to be the
11244 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000011245 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000011246 break;
11247
Chandler Carruth8e543b32010-12-12 08:17:55 +000011248 // For class as left operand for assignment or compound assigment
11249 // operator do not fall through to handling in built-in, but report that
11250 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000011251 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011252 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000011253 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000011254 Diag(OpLoc, diag::err_ovl_no_viable_oper)
11255 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000011256 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000011257 if (Args[0]->getType()->isIncompleteType()) {
11258 Diag(OpLoc, diag::note_assign_lhs_incomplete)
11259 << Args[0]->getType()
11260 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11261 }
Douglas Gregor66950a32009-09-30 21:46:01 +000011262 } else {
Richard Smith998a5912011-06-05 22:42:48 +000011263 // This is an erroneous use of an operator which can be overloaded by
11264 // a non-member function. Check for non-member operators which were
11265 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011266 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000011267 // FIXME: Recover by calling the found function.
11268 return ExprError();
11269
Douglas Gregor66950a32009-09-30 21:46:01 +000011270 // No viable function; try to create a built-in operation, which will
11271 // produce an error. Then, show the non-viable candidates.
11272 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000011273 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011274 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000011275 "C++ binary operator overloading is missing candidates!");
11276 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011277 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011278 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011279 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000011280 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011281
11282 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011283 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011284 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000011285 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000011286 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011287 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011288 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011289 return ExprError();
11290
11291 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000011292 if (isImplicitlyDeleted(Best->Function)) {
11293 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11294 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000011295 << Context.getRecordType(Method->getParent())
11296 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000011297
Richard Smithde1a4872012-12-28 12:23:24 +000011298 // The user probably meant to call this special member. Just
11299 // explain why it's deleted.
11300 NoteDeletedFunction(Method);
11301 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000011302 } else {
11303 Diag(OpLoc, diag::err_ovl_deleted_oper)
11304 << Best->Function->isDeleted()
11305 << BinaryOperator::getOpcodeStr(Opc)
11306 << getDeletedOrUnavailableSuffix(Best->Function)
11307 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11308 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011309 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011310 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011311 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000011312 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011313
Douglas Gregor66950a32009-09-30 21:46:01 +000011314 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000011315 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011316}
11317
John McCalldadc5752010-08-24 06:29:42 +000011318ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000011319Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11320 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000011321 Expr *Base, Expr *Idx) {
11322 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000011323 DeclarationName OpName =
11324 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11325
11326 // If either side is type-dependent, create an appropriate dependent
11327 // expression.
11328 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11329
Craig Topperc3ec1492014-05-26 06:22:03 +000011330 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011331 // CHECKME: no 'operator' keyword?
11332 DeclarationNameInfo OpNameInfo(OpName, LLoc);
11333 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000011334 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011335 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011336 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011337 /*ADL*/ true, /*Overloaded*/ false,
11338 UnresolvedSetIterator(),
11339 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000011340 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000011341
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011342 return new (Context)
11343 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11344 Context.DependentTy, VK_RValue, RLoc, false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011345 }
11346
John McCall4124c492011-10-17 18:40:02 +000011347 // Handle placeholders on both operands.
11348 if (checkPlaceholderForOverload(*this, Args[0]))
11349 return ExprError();
11350 if (checkPlaceholderForOverload(*this, Args[1]))
11351 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011352
Sebastian Redladba46e2009-10-29 20:17:01 +000011353 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011354 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redladba46e2009-10-29 20:17:01 +000011355
11356 // Subscript can only be overloaded as a member function.
11357
11358 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011359 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011360
11361 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011362 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011363
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011364 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11365
Sebastian Redladba46e2009-10-29 20:17:01 +000011366 // Perform overload resolution.
11367 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011368 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000011369 case OR_Success: {
11370 // We found a built-in operator or an overloaded operator.
11371 FunctionDecl *FnDecl = Best->Function;
11372
11373 if (FnDecl) {
11374 // We matched an overloaded operator. Build a call to that
11375 // operator.
11376
John McCalla0296f72010-03-19 07:35:19 +000011377 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000011378
Sebastian Redladba46e2009-10-29 20:17:01 +000011379 // Convert the arguments.
11380 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000011381 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011382 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011383 Best->FoundDecl, Method);
11384 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011385 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011386 Args[0] = Arg0.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011387
Anders Carlssona68e51e2010-01-29 18:37:50 +000011388 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011389 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000011390 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011391 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000011392 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011393 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011394 Args[1]);
Anders Carlssona68e51e2010-01-29 18:37:50 +000011395 if (InputInit.isInvalid())
11396 return ExprError();
11397
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011398 Args[1] = InputInit.getAs<Expr>();
Anders Carlssona68e51e2010-01-29 18:37:50 +000011399
Sebastian Redladba46e2009-10-29 20:17:01 +000011400 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011401 DeclarationNameInfo OpLocInfo(OpName, LLoc);
11402 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011403 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011404 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011405 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011406 OpLocInfo.getLoc(),
11407 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011408 if (FnExpr.isInvalid())
11409 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011410
Richard Smithc1564702013-11-15 02:58:23 +000011411 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000011412 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011413 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11414 ResultTy = ResultTy.getNonLValueExprType(Context);
11415
John McCallb268a282010-08-23 23:25:46 +000011416 CXXOperatorCallExpr *TheCall =
11417 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011418 FnExpr.get(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000011419 ResultTy, VK, RLoc,
11420 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011421
Alp Toker314cc812014-01-25 16:55:45 +000011422 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000011423 return ExprError();
11424
John McCallb268a282010-08-23 23:25:46 +000011425 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000011426 } else {
11427 // We matched a built-in operator. Convert the arguments, then
11428 // break out so that we will build the appropriate built-in
11429 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011430 ExprResult ArgsRes0 =
11431 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11432 Best->Conversions[0], AA_Passing);
11433 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011434 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011435 Args[0] = ArgsRes0.get();
John Wiegley01296292011-04-08 18:41:53 +000011436
11437 ExprResult ArgsRes1 =
11438 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11439 Best->Conversions[1], AA_Passing);
11440 if (ArgsRes1.isInvalid())
11441 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011442 Args[1] = ArgsRes1.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011443
11444 break;
11445 }
11446 }
11447
11448 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000011449 if (CandidateSet.empty())
11450 Diag(LLoc, diag::err_ovl_no_oper)
11451 << Args[0]->getType() << /*subscript*/ 0
11452 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11453 else
11454 Diag(LLoc, diag::err_ovl_no_viable_subscript)
11455 << Args[0]->getType()
11456 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011457 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011458 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000011459 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011460 }
11461
11462 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011463 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011464 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000011465 << Args[0]->getType() << Args[1]->getType()
11466 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011467 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011468 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011469 return ExprError();
11470
11471 case OR_Deleted:
11472 Diag(LLoc, diag::err_ovl_deleted_oper)
11473 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011474 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000011475 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011476 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011477 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011478 return ExprError();
11479 }
11480
11481 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000011482 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011483}
11484
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011485/// BuildCallToMemberFunction - Build a call to a member
11486/// function. MemExpr is the expression that refers to the member
11487/// function (and includes the object parameter), Args/NumArgs are the
11488/// arguments to the function call (not including the object
11489/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000011490/// expression refers to a non-static member function or an overloaded
11491/// member function.
John McCalldadc5752010-08-24 06:29:42 +000011492ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000011493Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011494 SourceLocation LParenLoc,
11495 MultiExprArg Args,
11496 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000011497 assert(MemExprE->getType() == Context.BoundMemberTy ||
11498 MemExprE->getType() == Context.OverloadTy);
11499
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011500 // Dig out the member expression. This holds both the object
11501 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000011502 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011503
John McCall0009fcc2011-04-26 20:42:42 +000011504 // Determine whether this is a call to a pointer-to-member function.
11505 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11506 assert(op->getType() == Context.BoundMemberTy);
11507 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
11508
11509 QualType fnType =
11510 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11511
11512 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11513 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000011514 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000011515
11516 // Check that the object type isn't more qualified than the
11517 // member function we're calling.
11518 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11519
11520 QualType objectType = op->getLHS()->getType();
11521 if (op->getOpcode() == BO_PtrMemI)
11522 objectType = objectType->castAs<PointerType>()->getPointeeType();
11523 Qualifiers objectQuals = objectType.getQualifiers();
11524
11525 Qualifiers difference = objectQuals - funcQuals;
11526 difference.removeObjCGCAttr();
11527 difference.removeAddressSpace();
11528 if (difference) {
11529 std::string qualsString = difference.getAsString();
11530 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11531 << fnType.getUnqualifiedType()
11532 << qualsString
11533 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11534 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011535
David Majnemerb3e56542014-08-07 22:56:13 +000011536 if (resultType->isMemberPointerType())
11537 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11538 RequireCompleteType(LParenLoc, resultType, 0);
11539
John McCall0009fcc2011-04-26 20:42:42 +000011540 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011541 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000011542 resultType, valueKind, RParenLoc);
11543
Alp Toker314cc812014-01-25 16:55:45 +000011544 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +000011545 call, nullptr))
John McCall0009fcc2011-04-26 20:42:42 +000011546 return ExprError();
11547
Craig Topperc3ec1492014-05-26 06:22:03 +000011548 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000011549 return ExprError();
11550
Richard Trieu9be9c682013-06-22 02:30:38 +000011551 if (CheckOtherCall(call, proto))
11552 return ExprError();
11553
John McCall0009fcc2011-04-26 20:42:42 +000011554 return MaybeBindToTemporary(call);
11555 }
11556
John McCall4124c492011-10-17 18:40:02 +000011557 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011558 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000011559 return ExprError();
11560
John McCall10eae182009-11-30 22:42:35 +000011561 MemberExpr *MemExpr;
Craig Topperc3ec1492014-05-26 06:22:03 +000011562 CXXMethodDecl *Method = nullptr;
11563 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
11564 NestedNameSpecifier *Qualifier = nullptr;
John McCall10eae182009-11-30 22:42:35 +000011565 if (isa<MemberExpr>(NakedMemExpr)) {
11566 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000011567 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000011568 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011569 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000011570 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000011571 } else {
11572 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011573 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011574
John McCall6e9f8f62009-12-03 04:06:58 +000011575 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000011576 Expr::Classification ObjectClassification
11577 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11578 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000011579
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011580 // Add overload candidates
Richard Smith100b24a2014-04-17 01:52:14 +000011581 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
11582 OverloadCandidateSet::CSK_Normal);
Mike Stump11289f42009-09-09 15:08:12 +000011583
John McCall2d74de92009-12-01 22:10:20 +000011584 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000011585 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000011586 if (UnresExpr->hasExplicitTemplateArgs()) {
11587 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11588 TemplateArgs = &TemplateArgsBuffer;
11589 }
11590
John McCall10eae182009-11-30 22:42:35 +000011591 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11592 E = UnresExpr->decls_end(); I != E; ++I) {
11593
John McCall6e9f8f62009-12-03 04:06:58 +000011594 NamedDecl *Func = *I;
11595 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11596 if (isa<UsingShadowDecl>(Func))
11597 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11598
Douglas Gregor02824322011-01-26 19:30:28 +000011599
Francois Pichet64225792011-01-18 05:04:39 +000011600 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011601 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011602 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011603 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000011604 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000011605 // If explicit template arguments were provided, we can't call a
11606 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000011607 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000011608 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011609
John McCalla0296f72010-03-19 07:35:19 +000011610 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011611 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000011612 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000011613 } else {
John McCall10eae182009-11-30 22:42:35 +000011614 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000011615 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011616 ObjectType, ObjectClassification,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011617 Args, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000011618 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000011619 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000011620 }
Mike Stump11289f42009-09-09 15:08:12 +000011621
John McCall10eae182009-11-30 22:42:35 +000011622 DeclarationName DeclName = UnresExpr->getMemberName();
11623
John McCall4124c492011-10-17 18:40:02 +000011624 UnbridgedCasts.restore();
11625
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011626 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011627 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000011628 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011629 case OR_Success:
11630 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000011631 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000011632 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011633 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11634 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000011635 // If FoundDecl is different from Method (such as if one is a template
11636 // and the other a specialization), make sure DiagnoseUseOfDecl is
11637 // called on both.
11638 // FIXME: This would be more comprehensively addressed by modifying
11639 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11640 // being used.
11641 if (Method != FoundDecl.getDecl() &&
11642 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11643 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011644 break;
11645
11646 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000011647 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011648 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000011649 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011650 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011651 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011652 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011653
11654 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000011655 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000011656 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011657 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011658 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011659 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000011660
11661 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000011662 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000011663 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011664 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011665 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011666 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011667 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000011668 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011669 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011670 }
11671
John McCall16df1e52010-03-30 21:47:33 +000011672 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000011673
John McCall2d74de92009-12-01 22:10:20 +000011674 // If overload resolution picked a static member, build a
11675 // non-member call based on that function.
11676 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011677 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11678 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000011679 }
11680
John McCall10eae182009-11-30 22:42:35 +000011681 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011682 }
11683
Alp Toker314cc812014-01-25 16:55:45 +000011684 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000011685 ExprValueKind VK = Expr::getValueKindForType(ResultType);
11686 ResultType = ResultType.getNonLValueExprType(Context);
11687
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011688 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011689 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011690 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000011691 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011692
Eli Bendersky291a57e2014-09-25 23:59:08 +000011693 // (CUDA B.1): Check for invalid calls between targets.
11694 if (getLangOpts().CUDA) {
11695 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
11696 if (CheckCUDATarget(Caller, Method)) {
11697 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
11698 << IdentifyCUDATarget(Method) << Method->getIdentifier()
11699 << IdentifyCUDATarget(Caller);
11700 return ExprError();
11701 }
11702 }
11703 }
11704
Anders Carlssonc4859ba2009-10-10 00:06:20 +000011705 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000011706 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000011707 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000011708 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011709
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011710 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000011711 // We only need to do this if there was actually an overload; otherwise
11712 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000011713 if (!Method->isStatic()) {
11714 ExprResult ObjectArg =
11715 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11716 FoundDecl, Method);
11717 if (ObjectArg.isInvalid())
11718 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011719 MemExpr->setBase(ObjectArg.get());
John Wiegley01296292011-04-08 18:41:53 +000011720 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011721
11722 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000011723 const FunctionProtoType *Proto =
11724 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011725 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011726 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000011727 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011728
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011729 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011730
Richard Smith55ce3522012-06-25 20:30:08 +000011731 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000011732 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000011733
Anders Carlsson47061ee2011-05-06 14:25:31 +000011734 if ((isa<CXXConstructorDecl>(CurContext) ||
11735 isa<CXXDestructorDecl>(CurContext)) &&
11736 TheCall->getMethodDecl()->isPure()) {
11737 const CXXMethodDecl *MD = TheCall->getMethodDecl();
11738
Chandler Carruth59259262011-06-27 08:31:58 +000011739 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +000011740 Diag(MemExpr->getLocStart(),
11741 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11742 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11743 << MD->getParent()->getDeclName();
11744
11745 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000011746 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000011747 }
John McCallb268a282010-08-23 23:25:46 +000011748 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011749}
11750
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011751/// BuildCallToObjectOfClassType - Build a call to an object of class
11752/// type (C++ [over.call.object]), which can end up invoking an
11753/// overloaded function call operator (@c operator()) or performing a
11754/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000011755ExprResult
John Wiegley01296292011-04-08 18:41:53 +000011756Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000011757 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011758 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011759 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000011760 if (checkPlaceholderForOverload(*this, Obj))
11761 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011762 ExprResult Object = Obj;
John McCall4124c492011-10-17 18:40:02 +000011763
11764 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011765 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000011766 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011767
Nico Weberb58e51c2014-11-19 05:21:39 +000011768 assert(Object.get()->getType()->isRecordType() &&
11769 "Requires object type argument");
John Wiegley01296292011-04-08 18:41:53 +000011770 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000011771
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011772 // C++ [over.call.object]p1:
11773 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000011774 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011775 // candidate functions includes at least the function call
11776 // operators of T. The function call operators of T are obtained by
11777 // ordinary lookup of the name operator() in the context of
11778 // (E).operator().
Richard Smith100b24a2014-04-17 01:52:14 +000011779 OverloadCandidateSet CandidateSet(LParenLoc,
11780 OverloadCandidateSet::CSK_Operator);
Douglas Gregor91f84212008-12-11 16:49:14 +000011781 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011782
John Wiegley01296292011-04-08 18:41:53 +000011783 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011784 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011785 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011786
John McCall27b18f82009-11-17 02:14:36 +000011787 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11788 LookupQualifiedName(R, Record->getDecl());
11789 R.suppressDiagnostics();
11790
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011791 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000011792 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000011793 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011794 Object.get()->Classify(Context),
11795 Args, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000011796 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000011797 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011798
Douglas Gregorab7897a2008-11-19 22:57:39 +000011799 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011800 // In addition, for each (non-explicit in C++0x) conversion function
11801 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000011802 //
11803 // operator conversion-type-id () cv-qualifier;
11804 //
11805 // where cv-qualifier is the same cv-qualification as, or a
11806 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000011807 // denotes the type "pointer to function of (P1,...,Pn) returning
11808 // R", or the type "reference to pointer to function of
11809 // (P1,...,Pn) returning R", or the type "reference to function
11810 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000011811 // is also considered as a candidate function. Similarly,
11812 // surrogate call functions are added to the set of candidate
11813 // functions for each conversion function declared in an
11814 // accessible base class provided the function is not hidden
11815 // within T by another intervening declaration.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000011816 std::pair<CXXRecordDecl::conversion_iterator,
11817 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregor21591822010-01-11 19:36:35 +000011818 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000011819 for (CXXRecordDecl::conversion_iterator
11820 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000011821 NamedDecl *D = *I;
11822 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11823 if (isa<UsingShadowDecl>(D))
11824 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011825
Douglas Gregor74ba25c2009-10-21 06:18:39 +000011826 // Skip over templated conversion functions; they aren't
11827 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000011828 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000011829 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000011830
John McCall6e9f8f62009-12-03 04:06:58 +000011831 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011832 if (!Conv->isExplicit()) {
11833 // Strip the reference type (if any) and then the pointer type (if
11834 // any) to get down to what might be a function type.
11835 QualType ConvType = Conv->getConversionType().getNonReferenceType();
11836 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11837 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000011838
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011839 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11840 {
11841 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011842 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011843 }
11844 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000011845 }
Mike Stump11289f42009-09-09 15:08:12 +000011846
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011847 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11848
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011849 // Perform overload resolution.
11850 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000011851 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000011852 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011853 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000011854 // Overload resolution succeeded; we'll build the appropriate call
11855 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011856 break;
11857
11858 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000011859 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011860 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000011861 << Object.get()->getType() << /*call*/ 1
11862 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000011863 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011864 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000011865 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000011866 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011867 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011868 break;
11869
11870 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011871 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011872 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000011873 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011874 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011875 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011876
11877 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011878 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000011879 diag::err_ovl_deleted_object_call)
11880 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000011881 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011882 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000011883 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011884 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000011885 break;
Mike Stump11289f42009-09-09 15:08:12 +000011886 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011887
Douglas Gregorb412e172010-07-25 18:17:45 +000011888 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011889 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011890
John McCall4124c492011-10-17 18:40:02 +000011891 UnbridgedCasts.restore();
11892
Craig Topperc3ec1492014-05-26 06:22:03 +000011893 if (Best->Function == nullptr) {
Douglas Gregorab7897a2008-11-19 22:57:39 +000011894 // Since there is no function declaration, this is one of the
11895 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000011896 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000011897 = cast<CXXConversionDecl>(
11898 Best->Conversions[0].UserDefined.ConversionFunction);
11899
Craig Topperc3ec1492014-05-26 06:22:03 +000011900 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
11901 Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011902 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11903 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000011904 assert(Conv == Best->FoundDecl.getDecl() &&
11905 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000011906 // We selected one of the surrogate functions that converts the
11907 // object parameter to a function pointer. Perform the conversion
11908 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011909
Fariborz Jahanian774cf792009-09-28 18:35:46 +000011910 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000011911 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011912 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11913 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000011914 if (Call.isInvalid())
11915 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000011916 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011917 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
11918 CK_UserDefinedConversion, Call.get(),
11919 nullptr, VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011920
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011921 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000011922 }
11923
Craig Topperc3ec1492014-05-26 06:22:03 +000011924 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000011925
Douglas Gregorab7897a2008-11-19 22:57:39 +000011926 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11927 // that calls this method, using Object for the implicit object
11928 // parameter and passing along the remaining arguments.
11929 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000011930
11931 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000011932 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000011933 return ExprError();
11934
Chandler Carruth8e543b32010-12-12 08:17:55 +000011935 const FunctionProtoType *Proto =
11936 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011937
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011938 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000011939
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011940 DeclarationNameInfo OpLocInfo(
11941 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11942 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000011943 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011944 HadMultipleCandidates,
11945 OpLocInfo.getLoc(),
11946 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011947 if (NewFn.isInvalid())
11948 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011949
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000011950 // Build the full argument list for the method call (the implicit object
11951 // parameter is placed at the beginning of the list).
Ahmed Charlesaf94d562014-03-09 11:34:25 +000011952 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000011953 MethodArgs[0] = Object.get();
11954 std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
11955
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011956 // Once we've built TheCall, all of the expressions are properly
11957 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000011958 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000011959 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11960 ResultTy = ResultTy.getNonLValueExprType(Context);
11961
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000011962 CXXOperatorCallExpr *TheCall = new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011963 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000011964 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
11965 ResultTy, VK, RParenLoc, false);
11966 MethodArgs.reset();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011967
Alp Toker314cc812014-01-25 16:55:45 +000011968 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000011969 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011970
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011971 // We may have default arguments. If so, we need to allocate more
11972 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011973 if (Args.size() < NumParams)
11974 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011975
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011976 bool IsError = false;
11977
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011978 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000011979 ExprResult ObjRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000011980 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011981 Best->FoundDecl, Method);
11982 if (ObjRes.isInvalid())
11983 IsError = true;
11984 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011985 Object = ObjRes;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011986 TheCall->setArg(0, Object.get());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011987
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011988 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011989 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011990 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011991 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011992 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000011993
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011994 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011995
John McCalldadc5752010-08-24 06:29:42 +000011996 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011997 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011998 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011999 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000012000 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012001
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012002 IsError |= InputInit.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012003 Arg = InputInit.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012004 } else {
John McCalldadc5752010-08-24 06:29:42 +000012005 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000012006 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12007 if (DefArg.isInvalid()) {
12008 IsError = true;
12009 break;
12010 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012011
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012012 Arg = DefArg.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012013 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012014
12015 TheCall->setArg(i + 1, Arg);
12016 }
12017
12018 // If this is a variadic call, handle args passed through "...".
12019 if (Proto->isVariadic()) {
12020 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012021 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012022 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12023 nullptr);
John Wiegley01296292011-04-08 18:41:53 +000012024 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012025 TheCall->setArg(i + 1, Arg.get());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012026 }
12027 }
12028
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012029 if (IsError) return true;
12030
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012031 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012032
Richard Smith55ce3522012-06-25 20:30:08 +000012033 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000012034 return true;
12035
John McCalle172be52010-08-24 06:09:16 +000012036 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012037}
12038
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012039/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000012040/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012041/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000012042ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012043Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12044 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000012045 assert(Base->getType()->isRecordType() &&
12046 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000012047
John McCall4124c492011-10-17 18:40:02 +000012048 if (checkPlaceholderForOverload(*this, Base))
12049 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012050
John McCallbc077cf2010-02-08 23:07:23 +000012051 SourceLocation Loc = Base->getExprLoc();
12052
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012053 // C++ [over.ref]p1:
12054 //
12055 // [...] An expression x->m is interpreted as (x.operator->())->m
12056 // for a class object x of type T if T::operator->() exists and if
12057 // the operator is selected as the best match function by the
12058 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000012059 DeclarationName OpName =
12060 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Richard Smith100b24a2014-04-17 01:52:14 +000012061 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000012062 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000012063
John McCallbc077cf2010-02-08 23:07:23 +000012064 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012065 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000012066 return ExprError();
12067
John McCall27b18f82009-11-17 02:14:36 +000012068 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12069 LookupQualifiedName(R, BaseRecord->getDecl());
12070 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000012071
12072 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000012073 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000012074 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000012075 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000012076 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012077
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012078 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12079
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012080 // Perform overload resolution.
12081 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012082 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012083 case OR_Success:
12084 // Overload resolution succeeded; we'll build the call below.
12085 break;
12086
12087 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012088 if (CandidateSet.empty()) {
12089 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012090 if (NoArrowOperatorFound) {
12091 // Report this specific error to the caller instead of emitting a
12092 // diagnostic, as requested.
12093 *NoArrowOperatorFound = true;
12094 return ExprError();
12095 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012096 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12097 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012098 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012099 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012100 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012101 }
12102 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012103 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000012104 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012105 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012106 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012107
12108 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012109 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12110 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012111 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012112 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012113
12114 case OR_Deleted:
12115 Diag(OpLoc, diag::err_ovl_deleted_oper)
12116 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012117 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012118 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012119 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012120 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012121 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012122 }
12123
Craig Topperc3ec1492014-05-26 06:22:03 +000012124 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCalla0296f72010-03-19 07:35:19 +000012125
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012126 // Convert the object parameter.
12127 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000012128 ExprResult BaseResult =
Craig Topperc3ec1492014-05-26 06:22:03 +000012129 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012130 Best->FoundDecl, Method);
12131 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000012132 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012133 Base = BaseResult.get();
Douglas Gregor9ecea262008-11-21 03:04:22 +000012134
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012135 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000012136 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012137 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012138 if (FnExpr.isInvalid())
12139 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012140
Alp Toker314cc812014-01-25 16:55:45 +000012141 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012142 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12143 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000012144 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012145 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012146 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012147
Alp Toker314cc812014-01-25 16:55:45 +000012148 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012149 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000012150
12151 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012152}
12153
Richard Smithbcc22fc2012-03-09 08:00:36 +000012154/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12155/// a literal operator described by the provided lookup results.
12156ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12157 DeclarationNameInfo &SuffixInfo,
12158 ArrayRef<Expr*> Args,
12159 SourceLocation LitEndLoc,
12160 TemplateArgumentListInfo *TemplateArgs) {
12161 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000012162
Richard Smith100b24a2014-04-17 01:52:14 +000012163 OverloadCandidateSet CandidateSet(UDSuffixLoc,
12164 OverloadCandidateSet::CSK_Normal);
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000012165 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12166 /*SuppressUserConversions=*/true);
Richard Smithc67fdd42012-03-07 08:35:16 +000012167
Richard Smithbcc22fc2012-03-09 08:00:36 +000012168 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12169
Richard Smithbcc22fc2012-03-09 08:00:36 +000012170 // Perform overload resolution. This will usually be trivial, but might need
12171 // to perform substitutions for a literal operator template.
12172 OverloadCandidateSet::iterator Best;
12173 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12174 case OR_Success:
12175 case OR_Deleted:
12176 break;
12177
12178 case OR_No_Viable_Function:
12179 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12180 << R.getLookupName();
12181 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12182 return ExprError();
12183
12184 case OR_Ambiguous:
12185 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12186 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12187 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000012188 }
12189
Richard Smithbcc22fc2012-03-09 08:00:36 +000012190 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000012191 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12192 HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000012193 SuffixInfo.getLoc(),
12194 SuffixInfo.getInfo());
12195 if (Fn.isInvalid())
12196 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000012197
12198 // Check the argument types. This should almost always be a no-op, except
12199 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000012200 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000012201 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000012202 ExprResult InputInit = PerformCopyInitialization(
12203 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12204 SourceLocation(), Args[ArgIdx]);
12205 if (InputInit.isInvalid())
12206 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012207 ConvArgs[ArgIdx] = InputInit.get();
Richard Smithc67fdd42012-03-07 08:35:16 +000012208 }
12209
Alp Toker314cc812014-01-25 16:55:45 +000012210 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000012211 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12212 ResultTy = ResultTy.getNonLValueExprType(Context);
12213
Richard Smithc67fdd42012-03-07 08:35:16 +000012214 UserDefinedLiteral *UDL =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012215 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000012216 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000012217 ResultTy, VK, LitEndLoc, UDSuffixLoc);
12218
Alp Toker314cc812014-01-25 16:55:45 +000012219 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000012220 return ExprError();
12221
Craig Topperc3ec1492014-05-26 06:22:03 +000012222 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smithc67fdd42012-03-07 08:35:16 +000012223 return ExprError();
12224
12225 return MaybeBindToTemporary(UDL);
12226}
12227
Sam Panzer0f384432012-08-21 00:52:01 +000012228/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12229/// given LookupResult is non-empty, it is assumed to describe a member which
12230/// will be invoked. Otherwise, the function will be found via argument
12231/// dependent lookup.
12232/// CallExpr is set to a valid expression and FRS_Success returned on success,
12233/// otherwise CallExpr is set to ExprError() and some non-success value
12234/// is returned.
12235Sema::ForRangeStatus
12236Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
12237 SourceLocation RangeLoc, VarDecl *Decl,
12238 BeginEndFunction BEF,
12239 const DeclarationNameInfo &NameInfo,
12240 LookupResult &MemberLookup,
12241 OverloadCandidateSet *CandidateSet,
12242 Expr *Range, ExprResult *CallExpr) {
12243 CandidateSet->clear();
12244 if (!MemberLookup.empty()) {
12245 ExprResult MemberRef =
12246 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12247 /*IsPtr=*/false, CXXScopeSpec(),
12248 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012249 /*FirstQualifierInScope=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012250 MemberLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +000012251 /*TemplateArgs=*/nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000012252 if (MemberRef.isInvalid()) {
12253 *CallExpr = ExprError();
12254 Diag(Range->getLocStart(), diag::note_in_for_range)
12255 << RangeLoc << BEF << Range->getType();
12256 return FRS_DiagnosticIssued;
12257 }
Craig Topperc3ec1492014-05-26 06:22:03 +000012258 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000012259 if (CallExpr->isInvalid()) {
12260 *CallExpr = ExprError();
12261 Diag(Range->getLocStart(), diag::note_in_for_range)
12262 << RangeLoc << BEF << Range->getType();
12263 return FRS_DiagnosticIssued;
12264 }
12265 } else {
12266 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000012267 UnresolvedLookupExpr *Fn =
Craig Topperc3ec1492014-05-26 06:22:03 +000012268 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012269 NestedNameSpecifierLoc(), NameInfo,
12270 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000012271 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000012272
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012273 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000012274 CandidateSet, CallExpr);
12275 if (CandidateSet->empty() || CandidateSetError) {
12276 *CallExpr = ExprError();
12277 return FRS_NoViableFunction;
12278 }
12279 OverloadCandidateSet::iterator Best;
12280 OverloadingResult OverloadResult =
12281 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12282
12283 if (OverloadResult == OR_No_Viable_Function) {
12284 *CallExpr = ExprError();
12285 return FRS_NoViableFunction;
12286 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012287 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Craig Topperc3ec1492014-05-26 06:22:03 +000012288 Loc, nullptr, CandidateSet, &Best,
Sam Panzer0f384432012-08-21 00:52:01 +000012289 OverloadResult,
12290 /*AllowTypoCorrection=*/false);
12291 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12292 *CallExpr = ExprError();
12293 Diag(Range->getLocStart(), diag::note_in_for_range)
12294 << RangeLoc << BEF << Range->getType();
12295 return FRS_DiagnosticIssued;
12296 }
12297 }
12298 return FRS_Success;
12299}
12300
12301
Douglas Gregorcd695e52008-11-10 20:40:00 +000012302/// FixOverloadedFunctionReference - E is an expression that refers to
12303/// a C++ overloaded function (possibly with some parentheses and
12304/// perhaps a '&' around it). We have resolved the overloaded function
12305/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000012306/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000012307Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000012308 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000012309 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012310 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12311 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012312 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012313 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012314
Douglas Gregor51c538b2009-11-20 19:42:02 +000012315 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012316 }
12317
Douglas Gregor51c538b2009-11-20 19:42:02 +000012318 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012319 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12320 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012321 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000012322 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000012323 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000012324 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000012325 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012326 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012327
12328 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000012329 ICE->getCastKind(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012330 SubExpr, nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000012331 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012332 }
12333
Douglas Gregor51c538b2009-11-20 19:42:02 +000012334 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000012335 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000012336 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012337 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12338 if (Method->isStatic()) {
12339 // Do nothing: static member functions aren't any different
12340 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000012341 } else {
Alp Toker028ed912013-12-06 17:56:43 +000012342 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000012343 // UnresolvedLookupExpr holding an overloaded member function
12344 // or template.
John McCall16df1e52010-03-30 21:47:33 +000012345 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12346 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000012347 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012348 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012349
John McCalld14a8642009-11-21 08:51:07 +000012350 assert(isa<DeclRefExpr>(SubExpr)
12351 && "fixed to something other than a decl ref");
12352 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12353 && "fixed to a member ref with no nested name qualifier");
12354
12355 // We have taken the address of a pointer to member
12356 // function. Perform the computation here so that we get the
12357 // appropriate pointer to member type.
12358 QualType ClassType
12359 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12360 QualType MemPtrType
12361 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12362
John McCall7decc9e2010-11-18 06:31:45 +000012363 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12364 VK_RValue, OK_Ordinary,
12365 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012366 }
12367 }
John McCall16df1e52010-03-30 21:47:33 +000012368 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12369 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012370 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012371 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012372
John McCalle3027922010-08-25 11:45:40 +000012373 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012374 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000012375 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012376 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012377 }
John McCalld14a8642009-11-21 08:51:07 +000012378
12379 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000012380 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012381 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCalle66edc12009-11-24 19:00:30 +000012382 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000012383 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12384 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000012385 }
12386
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012387 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12388 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012389 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012390 Fn,
John McCall113bee02012-03-10 09:33:50 +000012391 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012392 ULE->getNameLoc(),
12393 Fn->getType(),
12394 VK_LValue,
12395 Found.getDecl(),
12396 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012397 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012398 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12399 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000012400 }
12401
John McCall10eae182009-11-30 22:42:35 +000012402 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000012403 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012404 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012405 if (MemExpr->hasExplicitTemplateArgs()) {
12406 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12407 TemplateArgs = &TemplateArgsBuffer;
12408 }
John McCall6b51f282009-11-23 01:53:49 +000012409
John McCall2d74de92009-12-01 22:10:20 +000012410 Expr *Base;
12411
John McCall7decc9e2010-11-18 06:31:45 +000012412 // If we're filling in a static method where we used to have an
12413 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000012414 if (MemExpr->isImplicitAccess()) {
12415 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012416 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12417 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012418 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012419 Fn,
John McCall113bee02012-03-10 09:33:50 +000012420 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012421 MemExpr->getMemberLoc(),
12422 Fn->getType(),
12423 VK_LValue,
12424 Found.getDecl(),
12425 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012426 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012427 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
12428 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000012429 } else {
12430 SourceLocation Loc = MemExpr->getMemberLoc();
12431 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000012432 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000012433 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000012434 Base = new (Context) CXXThisExpr(Loc,
12435 MemExpr->getBaseType(),
12436 /*isImplicit=*/true);
12437 }
John McCall2d74de92009-12-01 22:10:20 +000012438 } else
John McCallc3007a22010-10-26 07:05:15 +000012439 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000012440
John McCall4adb38c2011-04-27 00:36:17 +000012441 ExprValueKind valueKind;
12442 QualType type;
12443 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12444 valueKind = VK_LValue;
12445 type = Fn->getType();
12446 } else {
12447 valueKind = VK_RValue;
12448 type = Context.BoundMemberTy;
12449 }
12450
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012451 MemberExpr *ME = MemberExpr::Create(Context, Base,
12452 MemExpr->isArrow(),
12453 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012454 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012455 Fn,
12456 Found,
12457 MemExpr->getMemberNameInfo(),
12458 TemplateArgs,
12459 type, valueKind, OK_Ordinary);
12460 ME->setHadMultipleCandidates(true);
Richard Smith4f6a2c42012-11-14 07:06:31 +000012461 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012462 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012463 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012464
John McCallc3007a22010-10-26 07:05:15 +000012465 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000012466}
12467
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012468ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000012469 DeclAccessPair Found,
12470 FunctionDecl *Fn) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012471 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor3e1e5272009-12-09 23:02:17 +000012472}