blob: 75a511403d217019d5f7c9467cf30eadd3d1a27c [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);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001101 OverloadingResult UserDefResult
1102 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001103 AllowExplicit, AllowObjCConversionOnExplicit);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001104
1105 if (UserDefResult == OR_Success) {
1106 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 }
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001134 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1135 ICS.setAmbiguous();
1136 ICS.Ambiguous.setFromType(From->getType());
1137 ICS.Ambiguous.setToType(ToType);
1138 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1139 Cand != Conversions.end(); ++Cand)
1140 if (Cand->Viable)
1141 ICS.Ambiguous.addConversion(Cand->Function);
1142 } else {
1143 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1144 }
1145
1146 return ICS;
1147}
1148
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001149/// TryImplicitConversion - Attempt to perform an implicit conversion
1150/// from the given expression (Expr) to the given type (ToType). This
1151/// function returns an implicit conversion sequence that can be used
1152/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001153///
1154/// void f(float f);
1155/// void g(int i) { f(i); }
1156///
1157/// this routine would produce an implicit conversion sequence to
1158/// describe the initialization of f from i, which will be a standard
1159/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1160/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1161//
1162/// Note that this routine only determines how the conversion can be
1163/// performed; it does not actually perform the conversion. As such,
1164/// it will not produce any diagnostics if no conversion is available,
1165/// but will instead return an implicit conversion sequence of kind
1166/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001167///
1168/// If @p SuppressUserConversions, then user-defined conversions are
1169/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001170/// If @p AllowExplicit, then explicit user-defined conversions are
1171/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001172///
1173/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1174/// writeback conversion, which allows __autoreleasing id* parameters to
1175/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001176static ImplicitConversionSequence
1177TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1178 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001179 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001180 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001181 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001182 bool AllowObjCWritebackConversion,
1183 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001184 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001185 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001186 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001187 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001188 return ICS;
1189 }
1190
David Blaikiebbafb8a2012-03-11 07:00:24 +00001191 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001192 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001193 return ICS;
1194 }
1195
Douglas Gregor836a7e82010-08-11 02:15:33 +00001196 // C++ [over.ics.user]p4:
1197 // A conversion of an expression of class type to the same class
1198 // type is given Exact Match rank, and a conversion of an
1199 // expression of class type to a base class of that type is
1200 // given Conversion rank, in spite of the fact that a copy/move
1201 // constructor (i.e., a user-defined conversion function) is
1202 // called for those cases.
1203 QualType FromType = From->getType();
1204 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001205 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1206 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001207 ICS.setStandard();
1208 ICS.Standard.setAsIdentityConversion();
1209 ICS.Standard.setFromType(FromType);
1210 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001211
Douglas Gregor5ab11652010-04-17 22:01:05 +00001212 // We don't actually check at this point whether there is a valid
1213 // copy/move constructor, since overloading just assumes that it
1214 // exists. When we actually perform initialization, we'll find the
1215 // appropriate constructor to copy the returned object, if needed.
Craig Topperc3ec1492014-05-26 06:22:03 +00001216 ICS.Standard.CopyConstructor = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001217
Douglas Gregor5ab11652010-04-17 22:01:05 +00001218 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001219 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001220 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001221
Douglas Gregor836a7e82010-08-11 02:15:33 +00001222 return ICS;
1223 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001224
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001225 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1226 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001227 AllowObjCWritebackConversion,
1228 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001229}
1230
John McCall31168b02011-06-15 23:02:42 +00001231ImplicitConversionSequence
1232Sema::TryImplicitConversion(Expr *From, QualType ToType,
1233 bool SuppressUserConversions,
1234 bool AllowExplicit,
1235 bool InOverloadResolution,
1236 bool CStyle,
1237 bool AllowObjCWritebackConversion) {
Richard Smith17c00b42014-11-12 01:24:00 +00001238 return ::TryImplicitConversion(*this, From, ToType,
1239 SuppressUserConversions, AllowExplicit,
1240 InOverloadResolution, CStyle,
1241 AllowObjCWritebackConversion,
1242 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001243}
1244
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001245/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001246/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001247/// converted expression. Flavor is the kind of conversion we're
1248/// performing, used in the error message. If @p AllowExplicit,
1249/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001250ExprResult
1251Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001252 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001253 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001254 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001255}
1256
John Wiegley01296292011-04-08 18:41:53 +00001257ExprResult
1258Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001259 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001260 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001261 if (checkPlaceholderForOverload(*this, From))
1262 return ExprError();
1263
John McCall31168b02011-06-15 23:02:42 +00001264 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1265 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001266 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001267 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001268 if (getLangOpts().ObjC1)
1269 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1270 ToType, From->getType(), From);
Richard Smith17c00b42014-11-12 01:24:00 +00001271 ICS = ::TryImplicitConversion(*this, From, ToType,
1272 /*SuppressUserConversions=*/false,
1273 AllowExplicit,
1274 /*InOverloadResolution=*/false,
1275 /*CStyle=*/false,
1276 AllowObjCWritebackConversion,
1277 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001278 return PerformImplicitConversion(From, ToType, ICS, Action);
1279}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001280
1281/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001282/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001283bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1284 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001285 if (Context.hasSameUnqualifiedType(FromType, ToType))
1286 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001287
John McCall991eb4b2010-12-21 00:44:39 +00001288 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1289 // where F adds one of the following at most once:
1290 // - a pointer
1291 // - a member pointer
1292 // - a block pointer
1293 CanQualType CanTo = Context.getCanonicalType(ToType);
1294 CanQualType CanFrom = Context.getCanonicalType(FromType);
1295 Type::TypeClass TyClass = CanTo->getTypeClass();
1296 if (TyClass != CanFrom->getTypeClass()) return false;
1297 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1298 if (TyClass == Type::Pointer) {
1299 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1300 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1301 } else if (TyClass == Type::BlockPointer) {
1302 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1303 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1304 } else if (TyClass == Type::MemberPointer) {
1305 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1306 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1307 } else {
1308 return false;
1309 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001310
John McCall991eb4b2010-12-21 00:44:39 +00001311 TyClass = CanTo->getTypeClass();
1312 if (TyClass != CanFrom->getTypeClass()) return false;
1313 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1314 return false;
1315 }
1316
1317 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1318 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1319 if (!EInfo.getNoReturn()) return false;
1320
1321 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1322 assert(QualType(FromFn, 0).isCanonical());
1323 if (QualType(FromFn, 0) != CanTo) return false;
1324
1325 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001326 return true;
1327}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001328
Douglas Gregor46188682010-05-18 22:42:18 +00001329/// \brief Determine whether the conversion from FromType to ToType is a valid
1330/// vector conversion.
1331///
1332/// \param ICK Will be set to the vector conversion kind, if this is a vector
1333/// conversion.
John McCall9b595db2014-02-04 23:58:19 +00001334static bool IsVectorConversion(Sema &S, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001335 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001336 // We need at least one of these types to be a vector type to have a vector
1337 // conversion.
1338 if (!ToType->isVectorType() && !FromType->isVectorType())
1339 return false;
1340
1341 // Identical types require no conversions.
John McCall9b595db2014-02-04 23:58:19 +00001342 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor46188682010-05-18 22:42:18 +00001343 return false;
1344
1345 // There are no conversions between extended vector types, only identity.
1346 if (ToType->isExtVectorType()) {
1347 // There are no conversions between extended vector types other than the
1348 // identity conversion.
1349 if (FromType->isExtVectorType())
1350 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001351
Douglas Gregor46188682010-05-18 22:42:18 +00001352 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001353 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001354 ICK = ICK_Vector_Splat;
1355 return true;
1356 }
1357 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001358
1359 // We can perform the conversion between vector types in the following cases:
1360 // 1)vector types are equivalent AltiVec and GCC vector types
1361 // 2)lax vector conversions are permitted and the vector types are of the
1362 // same size
1363 if (ToType->isVectorType() && FromType->isVectorType()) {
John McCall9b595db2014-02-04 23:58:19 +00001364 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1365 S.isLaxVectorConversion(FromType, ToType)) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001366 ICK = ICK_Vector_Conversion;
1367 return true;
1368 }
Douglas Gregor46188682010-05-18 22:42:18 +00001369 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001370
Douglas Gregor46188682010-05-18 22:42:18 +00001371 return false;
1372}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001373
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001374static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1375 bool InOverloadResolution,
1376 StandardConversionSequence &SCS,
1377 bool CStyle);
Douglas Gregorc79862f2012-04-12 17:51:55 +00001378
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001379/// IsStandardConversion - Determines whether there is a standard
1380/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1381/// expression From to the type ToType. Standard conversion sequences
1382/// only consider non-class types; for conversions that involve class
1383/// types, use TryImplicitConversion. If a conversion exists, SCS will
1384/// contain the standard conversion sequence required to perform this
1385/// conversion and this routine will return true. Otherwise, this
1386/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001387static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1388 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001389 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001390 bool CStyle,
1391 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001392 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001393
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001394 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001395 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001396 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001397 SCS.setFromType(FromType);
Craig Topperc3ec1492014-05-26 06:22:03 +00001398 SCS.CopyConstructor = nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001399
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001400 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001401 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001402 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001403 if (S.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001404 return false;
1405
Mike Stump11289f42009-09-09 15:08:12 +00001406 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001407 }
1408
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001409 // The first conversion can be an lvalue-to-rvalue conversion,
1410 // array-to-pointer conversion, or function-to-pointer conversion
1411 // (C++ 4p1).
1412
John McCall5c32be02010-08-24 20:38:10 +00001413 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001414 DeclAccessPair AccessPair;
1415 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001416 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001417 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001418 // We were able to resolve the address of the overloaded function,
1419 // so we can convert to the type of that function.
1420 FromType = Fn->getType();
Ehsan Akhgaric3ad3ba2014-07-22 20:20:14 +00001421 SCS.setFromType(FromType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001422
1423 // we can sometimes resolve &foo<int> regardless of ToType, so check
1424 // if the type matches (identity) or we are converting to bool
1425 if (!S.Context.hasSameUnqualifiedType(
1426 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1427 QualType resultTy;
1428 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001429 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001430 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1431 // otherwise, only a boolean conversion is standard
1432 if (!ToType->isBooleanType())
1433 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001434 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001435
Chandler Carruthffce2452011-03-29 08:08:18 +00001436 // Check if the "from" expression is taking the address of an overloaded
1437 // function and recompute the FromType accordingly. Take advantage of the
1438 // fact that non-static member functions *must* have such an address-of
1439 // expression.
1440 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1441 if (Method && !Method->isStatic()) {
1442 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1443 "Non-unary operator on non-static member address");
1444 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1445 == UO_AddrOf &&
1446 "Non-address-of operator on non-static member address");
1447 const Type *ClassType
1448 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1449 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001450 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1451 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1452 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001453 "Non-address-of operator for overloaded function expression");
1454 FromType = S.Context.getPointerType(FromType);
1455 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001456
Douglas Gregor980fb162010-04-29 18:24:40 +00001457 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001458 assert(S.Context.hasSameType(
1459 FromType,
1460 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001461 } else {
1462 return false;
1463 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001464 }
John McCall154a2fd2011-08-30 00:57:29 +00001465 // Lvalue-to-rvalue conversion (C++11 4.1):
1466 // A glvalue (3.10) of a non-function, non-array type T can
1467 // be converted to a prvalue.
1468 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001469 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001470 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001471 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001472 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001473
Douglas Gregorc79862f2012-04-12 17:51:55 +00001474 // C11 6.3.2.1p2:
1475 // ... if the lvalue has atomic type, the value has the non-atomic version
1476 // of the type of the lvalue ...
1477 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1478 FromType = Atomic->getValueType();
1479
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001480 // If T is a non-class type, the type of the rvalue is the
1481 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001482 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1483 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001484 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001485 } else if (FromType->isArrayType()) {
1486 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001487 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001488
1489 // An lvalue or rvalue of type "array of N T" or "array of unknown
1490 // bound of T" can be converted to an rvalue of type "pointer to
1491 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001492 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001493
John McCall5c32be02010-08-24 20:38:10 +00001494 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001495 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001496 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001497
1498 // For the purpose of ranking in overload resolution
1499 // (13.3.3.1.1), this conversion is considered an
1500 // array-to-pointer conversion followed by a qualification
1501 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001502 SCS.Second = ICK_Identity;
1503 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001504 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001505 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001506 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001507 }
John McCall086a4642010-11-24 05:12:34 +00001508 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001509 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001510 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001511
1512 // An lvalue of function type T can be converted to an rvalue of
1513 // type "pointer to T." The result is a pointer to the
1514 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001515 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001516 } else {
1517 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001518 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001519 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001520 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001521
1522 // The second conversion can be an integral promotion, floating
1523 // point promotion, integral conversion, floating point conversion,
1524 // floating-integral conversion, pointer conversion,
1525 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001526 // For overloading in C, this can also be a "compatible-type"
1527 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001528 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001529 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001530 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001531 // The unqualified versions of the types are the same: there's no
1532 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001533 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001534 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001535 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001536 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001537 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001538 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001539 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001540 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001541 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001542 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001543 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001544 SCS.Second = ICK_Complex_Promotion;
1545 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001546 } else if (ToType->isBooleanType() &&
1547 (FromType->isArithmeticType() ||
1548 FromType->isAnyPointerType() ||
1549 FromType->isBlockPointerType() ||
1550 FromType->isMemberPointerType() ||
1551 FromType->isNullPtrType())) {
1552 // Boolean conversions (C++ 4.12).
1553 SCS.Second = ICK_Boolean_Conversion;
1554 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001555 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001556 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001557 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001558 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001559 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001560 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001561 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001562 SCS.Second = ICK_Complex_Conversion;
1563 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001564 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1565 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001566 // Complex-real conversions (C99 6.3.1.7)
1567 SCS.Second = ICK_Complex_Real;
1568 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001569 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001570 // Floating point conversions (C++ 4.8).
1571 SCS.Second = ICK_Floating_Conversion;
1572 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001573 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001574 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001575 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001576 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001577 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001578 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001579 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001580 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001581 SCS.Second = ICK_Block_Pointer_Conversion;
1582 } else if (AllowObjCWritebackConversion &&
1583 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1584 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001585 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1586 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001587 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001588 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001589 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001590 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001591 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001592 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001593 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001594 SCS.Second = ICK_Pointer_Member;
John McCall9b595db2014-02-04 23:58:19 +00001595 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001596 SCS.Second = SecondICK;
1597 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001598 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001599 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001600 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001601 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001602 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001603 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001604 // Treat a conversion that strips "noreturn" as an identity conversion.
1605 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001606 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1607 InOverloadResolution,
1608 SCS, CStyle)) {
1609 SCS.Second = ICK_TransparentUnionConversion;
1610 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001611 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1612 CStyle)) {
1613 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001614 // appropriately.
1615 return true;
Guy Benyei259f9f42013-02-07 16:05:33 +00001616 } else if (ToType->isEventT() &&
1617 From->isIntegerConstantExpr(S.getASTContext()) &&
1618 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1619 SCS.Second = ICK_Zero_Event_Conversion;
1620 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001621 } else {
1622 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001623 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001624 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001625 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001626
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001627 QualType CanonFrom;
1628 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001629 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001630 bool ObjCLifetimeConversion;
1631 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1632 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001633 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001634 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001635 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001636 CanonFrom = S.Context.getCanonicalType(FromType);
1637 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001638 } else {
1639 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001640 SCS.Third = ICK_Identity;
1641
Mike Stump11289f42009-09-09 15:08:12 +00001642 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001643 // [...] Any difference in top-level cv-qualification is
1644 // subsumed by the initialization itself and does not constitute
1645 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001646 CanonFrom = S.Context.getCanonicalType(FromType);
1647 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001648 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001649 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault7d36c012013-02-26 21:15:54 +00001650 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001651 FromType = ToType;
1652 CanonFrom = CanonTo;
1653 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001654 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001655 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001656
1657 // If we have not converted the argument type to the parameter type,
1658 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001659 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001660 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001661
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001662 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001663}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001664
1665static bool
1666IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1667 QualType &ToType,
1668 bool InOverloadResolution,
1669 StandardConversionSequence &SCS,
1670 bool CStyle) {
1671
1672 const RecordType *UT = ToType->getAsUnionType();
1673 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1674 return false;
1675 // The field to initialize within the transparent union.
1676 RecordDecl *UD = UT->getDecl();
1677 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001678 for (const auto *it : UD->fields()) {
John McCall31168b02011-06-15 23:02:42 +00001679 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1680 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001681 ToType = it->getType();
1682 return true;
1683 }
1684 }
1685 return false;
1686}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001687
1688/// IsIntegralPromotion - Determines whether the conversion from the
1689/// expression From (whose potentially-adjusted type is FromType) to
1690/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1691/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001692bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001693 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001694 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001695 if (!To) {
1696 return false;
1697 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001698
1699 // An rvalue of type char, signed char, unsigned char, short int, or
1700 // unsigned short int can be converted to an rvalue of type int if
1701 // int can represent all the values of the source type; otherwise,
1702 // the source rvalue can be converted to an rvalue of type unsigned
1703 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001704 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1705 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001706 if (// We can promote any signed, promotable integer type to an int
1707 (FromType->isSignedIntegerType() ||
1708 // We can promote any unsigned integer type whose size is
1709 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001710 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001711 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001712 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001713 }
1714
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001715 return To->getKind() == BuiltinType::UInt;
1716 }
1717
Richard Smithb9c5a602012-09-13 21:18:54 +00001718 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001719 // A prvalue of an unscoped enumeration type whose underlying type is not
1720 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1721 // following types that can represent all the values of the enumeration
1722 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1723 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001724 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001725 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001726 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001727 // with lowest integer conversion rank (4.13) greater than the rank of long
1728 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001729 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001730 // C++11 [conv.prom]p4:
1731 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1732 // can be converted to a prvalue of its underlying type. Moreover, if
1733 // integral promotion can be applied to its underlying type, a prvalue of an
1734 // unscoped enumeration type whose underlying type is fixed can also be
1735 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001736 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1737 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1738 // provided for a scoped enumeration.
1739 if (FromEnumType->getDecl()->isScoped())
1740 return false;
1741
Richard Smithb9c5a602012-09-13 21:18:54 +00001742 // We can perform an integral promotion to the underlying type of the enum,
1743 // even if that's not the promoted type.
1744 if (FromEnumType->getDecl()->isFixed()) {
1745 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1746 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1747 IsIntegralPromotion(From, Underlying, ToType);
1748 }
1749
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001750 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001751 if (ToType->isIntegerType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001752 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall56774992009-12-09 09:09:27 +00001753 return Context.hasSameUnqualifiedType(ToType,
1754 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001755 }
John McCall56774992009-12-09 09:09:27 +00001756
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001757 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001758 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1759 // to an rvalue a prvalue of the first of the following types that can
1760 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001761 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001762 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001763 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001764 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001765 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001766 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001767 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001768 // Determine whether the type we're converting from is signed or
1769 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001770 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001771 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001772
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001773 // The types we'll try to promote to, in the appropriate
1774 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001775 QualType PromoteTypes[6] = {
1776 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001777 Context.LongTy, Context.UnsignedLongTy ,
1778 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001779 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001780 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001781 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1782 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001783 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001784 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1785 // We found the type that we can promote to. If this is the
1786 // type we wanted, we have a promotion. Otherwise, no
1787 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001788 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001789 }
1790 }
1791 }
1792
1793 // An rvalue for an integral bit-field (9.6) can be converted to an
1794 // rvalue of type int if int can represent all the values of the
1795 // bit-field; otherwise, it can be converted to unsigned int if
1796 // unsigned int can represent all the values of the bit-field. If
1797 // the bit-field is larger yet, no integral promotion applies to
1798 // it. If the bit-field has an enumerated type, it is treated as any
1799 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001800 // FIXME: We should delay checking of bit-fields until we actually perform the
1801 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001802 using llvm::APSInt;
1803 if (From)
John McCalld25db7e2013-05-06 21:39:12 +00001804 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001805 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001806 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001807 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1808 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1809 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001810
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001811 // Are we promoting to an int from a bitfield that fits in an int?
1812 if (BitWidth < ToSize ||
1813 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1814 return To->getKind() == BuiltinType::Int;
1815 }
Mike Stump11289f42009-09-09 15:08:12 +00001816
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001817 // Are we promoting to an unsigned int from an unsigned bitfield
1818 // that fits into an unsigned int?
1819 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1820 return To->getKind() == BuiltinType::UInt;
1821 }
Mike Stump11289f42009-09-09 15:08:12 +00001822
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001823 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001824 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001825 }
Mike Stump11289f42009-09-09 15:08:12 +00001826
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001827 // An rvalue of type bool can be converted to an rvalue of type int,
1828 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001829 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001830 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001831 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001832
1833 return false;
1834}
1835
1836/// IsFloatingPointPromotion - Determines whether the conversion from
1837/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1838/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001839bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001840 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1841 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001842 /// An rvalue of type float can be converted to an rvalue of type
1843 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001844 if (FromBuiltin->getKind() == BuiltinType::Float &&
1845 ToBuiltin->getKind() == BuiltinType::Double)
1846 return true;
1847
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001848 // C99 6.3.1.5p1:
1849 // When a float is promoted to double or long double, or a
1850 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00001851 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001852 (FromBuiltin->getKind() == BuiltinType::Float ||
1853 FromBuiltin->getKind() == BuiltinType::Double) &&
1854 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1855 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001856
1857 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00001858 if (!getLangOpts().NativeHalfType &&
1859 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001860 ToBuiltin->getKind() == BuiltinType::Float)
1861 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001862 }
1863
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001864 return false;
1865}
1866
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001867/// \brief Determine if a conversion is a complex promotion.
1868///
1869/// A complex promotion is defined as a complex -> complex conversion
1870/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001871/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001872bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001873 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001874 if (!FromComplex)
1875 return false;
1876
John McCall9dd450b2009-09-21 23:43:11 +00001877 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001878 if (!ToComplex)
1879 return false;
1880
1881 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001882 ToComplex->getElementType()) ||
Craig Topperc3ec1492014-05-26 06:22:03 +00001883 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001884 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001885}
1886
Douglas Gregor237f96c2008-11-26 23:31:11 +00001887/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1888/// the pointer type FromPtr to a pointer to type ToPointee, with the
1889/// same type qualifiers as FromPtr has on its pointee type. ToType,
1890/// if non-empty, will be a pointer to ToType that may or may not have
1891/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001892///
Mike Stump11289f42009-09-09 15:08:12 +00001893static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001894BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001895 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001896 ASTContext &Context,
1897 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001898 assert((FromPtr->getTypeClass() == Type::Pointer ||
1899 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1900 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001901
John McCall31168b02011-06-15 23:02:42 +00001902 /// Conversions to 'id' subsume cv-qualifier conversions.
1903 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001904 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001905
1906 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001907 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001908 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001909 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001910
John McCall31168b02011-06-15 23:02:42 +00001911 if (StripObjCLifetime)
1912 Quals.removeObjCLifetime();
1913
Mike Stump11289f42009-09-09 15:08:12 +00001914 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001915 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001916 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001917 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001918 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001919
1920 // Build a pointer to ToPointee. It has the right qualifiers
1921 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001922 if (isa<ObjCObjectPointerType>(ToType))
1923 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001924 return Context.getPointerType(ToPointee);
1925 }
1926
1927 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001928 QualType QualifiedCanonToPointee
1929 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001930
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001931 if (isa<ObjCObjectPointerType>(ToType))
1932 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1933 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001934}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001935
Mike Stump11289f42009-09-09 15:08:12 +00001936static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001937 bool InOverloadResolution,
1938 ASTContext &Context) {
1939 // Handle value-dependent integral null pointer constants correctly.
1940 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1941 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001942 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001943 return !InOverloadResolution;
1944
Douglas Gregor56751b52009-09-25 04:25:58 +00001945 return Expr->isNullPointerConstant(Context,
1946 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1947 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001948}
Mike Stump11289f42009-09-09 15:08:12 +00001949
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001950/// IsPointerConversion - Determines whether the conversion of the
1951/// expression From, which has the (possibly adjusted) type FromType,
1952/// can be converted to the type ToType via a pointer conversion (C++
1953/// 4.10). If so, returns true and places the converted type (that
1954/// might differ from ToType in its cv-qualifiers at some level) into
1955/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001956///
Douglas Gregora29dc052008-11-27 01:19:21 +00001957/// This routine also supports conversions to and from block pointers
1958/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1959/// pointers to interfaces. FIXME: Once we've determined the
1960/// appropriate overloading rules for Objective-C, we may want to
1961/// split the Objective-C checks into a different routine; however,
1962/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001963/// conversions, so for now they live here. IncompatibleObjC will be
1964/// set if the conversion is an allowed Objective-C conversion that
1965/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001966bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001967 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001968 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001969 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001970 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001971 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1972 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001973 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001974
Mike Stump11289f42009-09-09 15:08:12 +00001975 // Conversion from a null pointer constant to any Objective-C pointer type.
1976 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001977 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001978 ConvertedType = ToType;
1979 return true;
1980 }
1981
Douglas Gregor231d1c62008-11-27 00:15:41 +00001982 // Blocks: Block pointers can be converted to void*.
1983 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001984 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001985 ConvertedType = ToType;
1986 return true;
1987 }
1988 // Blocks: A null pointer constant can be converted to a block
1989 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001990 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001991 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001992 ConvertedType = ToType;
1993 return true;
1994 }
1995
Sebastian Redl576fd422009-05-10 18:38:11 +00001996 // If the left-hand-side is nullptr_t, the right side can be a null
1997 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001998 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001999 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002000 ConvertedType = ToType;
2001 return true;
2002 }
2003
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002004 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002005 if (!ToTypePtr)
2006 return false;
2007
2008 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002009 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002010 ConvertedType = ToType;
2011 return true;
2012 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002013
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002014 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002015 // , including objective-c pointers.
2016 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002017 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002018 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002019 ConvertedType = BuildSimilarlyQualifiedPointerType(
2020 FromType->getAs<ObjCObjectPointerType>(),
2021 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002022 ToType, Context);
2023 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002024 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002025 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002026 if (!FromTypePtr)
2027 return false;
2028
2029 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002030
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002031 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002032 // pointer conversion, so don't do all of the work below.
2033 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2034 return false;
2035
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002036 // An rvalue of type "pointer to cv T," where T is an object type,
2037 // can be converted to an rvalue of type "pointer to cv void" (C++
2038 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002039 if (FromPointeeType->isIncompleteOrObjectType() &&
2040 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002041 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002042 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002043 ToType, Context,
2044 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002045 return true;
2046 }
2047
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002048 // MSVC allows implicit function to void* type conversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002049 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002050 ToPointeeType->isVoidType()) {
2051 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2052 ToPointeeType,
2053 ToType, Context);
2054 return true;
2055 }
2056
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002057 // When we're overloading in C, we allow a special kind of pointer
2058 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002059 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002060 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002061 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002062 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002063 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002064 return true;
2065 }
2066
Douglas Gregor5c407d92008-10-23 00:40:37 +00002067 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002068 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002069 // An rvalue of type "pointer to cv D," where D is a class type,
2070 // can be converted to an rvalue of type "pointer to cv B," where
2071 // B is a base class (clause 10) of D. If B is an inaccessible
2072 // (clause 11) or ambiguous (10.2) base class of D, a program that
2073 // necessitates this conversion is ill-formed. The result of the
2074 // conversion is a pointer to the base class sub-object of the
2075 // derived class object. The null pointer value is converted to
2076 // the null pointer value of the destination type.
2077 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002078 // Note that we do not check for ambiguity or inaccessibility
2079 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002080 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002081 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002082 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002083 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00002084 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002085 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002086 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002087 ToType, Context);
2088 return true;
2089 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002090
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002091 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2092 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2093 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2094 ToPointeeType,
2095 ToType, Context);
2096 return true;
2097 }
2098
Douglas Gregora119f102008-12-19 19:13:09 +00002099 return false;
2100}
Douglas Gregoraec25842011-04-26 23:16:46 +00002101
2102/// \brief Adopt the given qualifiers for the given type.
2103static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2104 Qualifiers TQs = T.getQualifiers();
2105
2106 // Check whether qualifiers already match.
2107 if (TQs == Qs)
2108 return T;
2109
2110 if (Qs.compatiblyIncludes(TQs))
2111 return Context.getQualifiedType(T, Qs);
2112
2113 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2114}
Douglas Gregora119f102008-12-19 19:13:09 +00002115
2116/// isObjCPointerConversion - Determines whether this is an
2117/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2118/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002119bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002120 QualType& ConvertedType,
2121 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002122 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002123 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002124
Douglas Gregoraec25842011-04-26 23:16:46 +00002125 // The set of qualifiers on the type we're converting from.
2126 Qualifiers FromQualifiers = FromType.getQualifiers();
2127
Steve Naroff7cae42b2009-07-10 23:34:53 +00002128 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002129 const ObjCObjectPointerType* ToObjCPtr =
2130 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002131 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002132 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002133
Steve Naroff7cae42b2009-07-10 23:34:53 +00002134 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002135 // If the pointee types are the same (ignoring qualifications),
2136 // then this is not a pointer conversion.
2137 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2138 FromObjCPtr->getPointeeType()))
2139 return false;
2140
Douglas Gregoraec25842011-04-26 23:16:46 +00002141 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00002142 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00002143 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00002144 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002145 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002146 return true;
2147 }
2148 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00002149 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00002150 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00002151 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00002152 /*compare=*/false)) {
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 // Objective C++: We're able to convert from a pointer to an
2157 // interface to a pointer to a different interface.
2158 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002159 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2160 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002161 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002162 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2163 FromObjCPtr->getPointeeType()))
2164 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002165 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002166 ToObjCPtr->getPointeeType(),
2167 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002168 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002169 return true;
2170 }
2171
2172 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2173 // Okay: this is some kind of implicit downcast of Objective-C
2174 // interfaces, which is permitted. However, we're going to
2175 // complain about it.
2176 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002177 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002178 ToObjCPtr->getPointeeType(),
2179 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002180 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002181 return true;
2182 }
Mike Stump11289f42009-09-09 15:08:12 +00002183 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002184 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002185 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002186 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002187 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002188 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002189 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002190 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002191 // to a block pointer type.
2192 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002193 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002194 return true;
2195 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002196 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002197 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002198 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002199 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002200 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002201 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002202 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002203 return true;
2204 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002205 else
Douglas Gregora119f102008-12-19 19:13:09 +00002206 return false;
2207
Douglas Gregor033f56d2008-12-23 00:53:59 +00002208 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002209 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002210 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002211 else if (const BlockPointerType *FromBlockPtr =
2212 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002213 FromPointeeType = FromBlockPtr->getPointeeType();
2214 else
Douglas Gregora119f102008-12-19 19:13:09 +00002215 return false;
2216
Douglas Gregora119f102008-12-19 19:13:09 +00002217 // If we have pointers to pointers, recursively check whether this
2218 // is an Objective-C conversion.
2219 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2220 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2221 IncompatibleObjC)) {
2222 // We always complain about this conversion.
2223 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002224 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002225 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002226 return true;
2227 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002228 // Allow conversion of pointee being objective-c pointer to another one;
2229 // as in I* to id.
2230 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2231 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2232 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2233 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002234
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002235 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002236 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002237 return true;
2238 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002239
Douglas Gregor033f56d2008-12-23 00:53:59 +00002240 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002241 // differences in the argument and result types are in Objective-C
2242 // pointer conversions. If so, we permit the conversion (but
2243 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002244 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002245 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002246 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002247 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002248 if (FromFunctionType && ToFunctionType) {
2249 // If the function types are exactly the same, this isn't an
2250 // Objective-C pointer conversion.
2251 if (Context.getCanonicalType(FromPointeeType)
2252 == Context.getCanonicalType(ToPointeeType))
2253 return false;
2254
2255 // Perform the quick checks that will tell us whether these
2256 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002257 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002258 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2259 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2260 return false;
2261
2262 bool HasObjCConversion = false;
Alp Toker314cc812014-01-25 16:55:45 +00002263 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2264 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregora119f102008-12-19 19:13:09 +00002265 // Okay, the types match exactly. Nothing to do.
Alp Toker314cc812014-01-25 16:55:45 +00002266 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2267 ToFunctionType->getReturnType(),
Douglas Gregora119f102008-12-19 19:13:09 +00002268 ConvertedType, IncompatibleObjC)) {
2269 // Okay, we have an Objective-C pointer conversion.
2270 HasObjCConversion = true;
2271 } else {
2272 // Function types are too different. Abort.
2273 return false;
2274 }
Mike Stump11289f42009-09-09 15:08:12 +00002275
Douglas Gregora119f102008-12-19 19:13:09 +00002276 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002277 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002278 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002279 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2280 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002281 if (Context.getCanonicalType(FromArgType)
2282 == Context.getCanonicalType(ToArgType)) {
2283 // Okay, the types match exactly. Nothing to do.
2284 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2285 ConvertedType, IncompatibleObjC)) {
2286 // Okay, we have an Objective-C pointer conversion.
2287 HasObjCConversion = true;
2288 } else {
2289 // Argument types are too different. Abort.
2290 return false;
2291 }
2292 }
2293
2294 if (HasObjCConversion) {
2295 // We had an Objective-C conversion. Allow this pointer
2296 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002297 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002298 IncompatibleObjC = true;
2299 return true;
2300 }
2301 }
2302
Sebastian Redl72b597d2009-01-25 19:43:20 +00002303 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002304}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002305
John McCall31168b02011-06-15 23:02:42 +00002306/// \brief Determine whether this is an Objective-C writeback conversion,
2307/// used for parameter passing when performing automatic reference counting.
2308///
2309/// \param FromType The type we're converting form.
2310///
2311/// \param ToType The type we're converting to.
2312///
2313/// \param ConvertedType The type that will be produced after applying
2314/// this conversion.
2315bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2316 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002317 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002318 Context.hasSameUnqualifiedType(FromType, ToType))
2319 return false;
2320
2321 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2322 QualType ToPointee;
2323 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2324 ToPointee = ToPointer->getPointeeType();
2325 else
2326 return false;
2327
2328 Qualifiers ToQuals = ToPointee.getQualifiers();
2329 if (!ToPointee->isObjCLifetimeType() ||
2330 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002331 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002332 return false;
2333
2334 // Argument must be a pointer to __strong to __weak.
2335 QualType FromPointee;
2336 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2337 FromPointee = FromPointer->getPointeeType();
2338 else
2339 return false;
2340
2341 Qualifiers FromQuals = FromPointee.getQualifiers();
2342 if (!FromPointee->isObjCLifetimeType() ||
2343 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2344 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2345 return false;
2346
2347 // Make sure that we have compatible qualifiers.
2348 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2349 if (!ToQuals.compatiblyIncludes(FromQuals))
2350 return false;
2351
2352 // Remove qualifiers from the pointee type we're converting from; they
2353 // aren't used in the compatibility check belong, and we'll be adding back
2354 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2355 FromPointee = FromPointee.getUnqualifiedType();
2356
2357 // The unqualified form of the pointee types must be compatible.
2358 ToPointee = ToPointee.getUnqualifiedType();
2359 bool IncompatibleObjC;
2360 if (Context.typesAreCompatible(FromPointee, ToPointee))
2361 FromPointee = ToPointee;
2362 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2363 IncompatibleObjC))
2364 return false;
2365
2366 /// \brief Construct the type we're converting to, which is a pointer to
2367 /// __autoreleasing pointee.
2368 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2369 ConvertedType = Context.getPointerType(FromPointee);
2370 return true;
2371}
2372
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002373bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2374 QualType& ConvertedType) {
2375 QualType ToPointeeType;
2376 if (const BlockPointerType *ToBlockPtr =
2377 ToType->getAs<BlockPointerType>())
2378 ToPointeeType = ToBlockPtr->getPointeeType();
2379 else
2380 return false;
2381
2382 QualType FromPointeeType;
2383 if (const BlockPointerType *FromBlockPtr =
2384 FromType->getAs<BlockPointerType>())
2385 FromPointeeType = FromBlockPtr->getPointeeType();
2386 else
2387 return false;
2388 // We have pointer to blocks, check whether the only
2389 // differences in the argument and result types are in Objective-C
2390 // pointer conversions. If so, we permit the conversion.
2391
2392 const FunctionProtoType *FromFunctionType
2393 = FromPointeeType->getAs<FunctionProtoType>();
2394 const FunctionProtoType *ToFunctionType
2395 = ToPointeeType->getAs<FunctionProtoType>();
2396
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002397 if (!FromFunctionType || !ToFunctionType)
2398 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002399
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002400 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002401 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002402
2403 // Perform the quick checks that will tell us whether these
2404 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002405 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002406 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2407 return false;
2408
2409 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2410 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2411 if (FromEInfo != ToEInfo)
2412 return false;
2413
2414 bool IncompatibleObjC = false;
Alp Toker314cc812014-01-25 16:55:45 +00002415 if (Context.hasSameType(FromFunctionType->getReturnType(),
2416 ToFunctionType->getReturnType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002417 // Okay, the types match exactly. Nothing to do.
2418 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002419 QualType RHS = FromFunctionType->getReturnType();
2420 QualType LHS = ToFunctionType->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002421 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002422 !RHS.hasQualifiers() && LHS.hasQualifiers())
2423 LHS = LHS.getUnqualifiedType();
2424
2425 if (Context.hasSameType(RHS,LHS)) {
2426 // OK exact match.
2427 } else if (isObjCPointerConversion(RHS, LHS,
2428 ConvertedType, IncompatibleObjC)) {
2429 if (IncompatibleObjC)
2430 return false;
2431 // Okay, we have an Objective-C pointer conversion.
2432 }
2433 else
2434 return false;
2435 }
2436
2437 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002438 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002439 ArgIdx != NumArgs; ++ArgIdx) {
2440 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002441 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2442 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002443 if (Context.hasSameType(FromArgType, ToArgType)) {
2444 // Okay, the types match exactly. Nothing to do.
2445 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2446 ConvertedType, IncompatibleObjC)) {
2447 if (IncompatibleObjC)
2448 return false;
2449 // Okay, we have an Objective-C pointer conversion.
2450 } else
2451 // Argument types are too different. Abort.
2452 return false;
2453 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002454 if (LangOpts.ObjCAutoRefCount &&
2455 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2456 ToFunctionType))
2457 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002458
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002459 ConvertedType = ToType;
2460 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002461}
2462
Richard Trieucaff2472011-11-23 22:32:32 +00002463enum {
2464 ft_default,
2465 ft_different_class,
2466 ft_parameter_arity,
2467 ft_parameter_mismatch,
2468 ft_return_type,
2469 ft_qualifer_mismatch
2470};
2471
2472/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2473/// function types. Catches different number of parameter, mismatch in
2474/// parameter types, and different return types.
2475void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2476 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002477 // If either type is not valid, include no extra info.
2478 if (FromType.isNull() || ToType.isNull()) {
2479 PDiag << ft_default;
2480 return;
2481 }
2482
Richard Trieucaff2472011-11-23 22:32:32 +00002483 // Get the function type from the pointers.
2484 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2485 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2486 *ToMember = ToType->getAs<MemberPointerType>();
Richard Trieu9098c9f2014-05-22 01:39:16 +00002487 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
Richard Trieucaff2472011-11-23 22:32:32 +00002488 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2489 << QualType(FromMember->getClass(), 0);
2490 return;
2491 }
2492 FromType = FromMember->getPointeeType();
2493 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002494 }
2495
Richard Trieu96ed5b62011-12-13 23:19:45 +00002496 if (FromType->isPointerType())
2497 FromType = FromType->getPointeeType();
2498 if (ToType->isPointerType())
2499 ToType = ToType->getPointeeType();
2500
2501 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002502 FromType = FromType.getNonReferenceType();
2503 ToType = ToType.getNonReferenceType();
2504
Richard Trieucaff2472011-11-23 22:32:32 +00002505 // Don't print extra info for non-specialized template functions.
2506 if (FromType->isInstantiationDependentType() &&
2507 !FromType->getAs<TemplateSpecializationType>()) {
2508 PDiag << ft_default;
2509 return;
2510 }
2511
Richard Trieu96ed5b62011-12-13 23:19:45 +00002512 // No extra info for same types.
2513 if (Context.hasSameType(FromType, ToType)) {
2514 PDiag << ft_default;
2515 return;
2516 }
2517
Richard Trieucaff2472011-11-23 22:32:32 +00002518 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2519 *ToFunction = ToType->getAs<FunctionProtoType>();
2520
2521 // Both types need to be function types.
2522 if (!FromFunction || !ToFunction) {
2523 PDiag << ft_default;
2524 return;
2525 }
2526
Alp Toker9cacbab2014-01-20 20:26:09 +00002527 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2528 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2529 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002530 return;
2531 }
2532
2533 // Handle different parameter types.
2534 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002535 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002536 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002537 << ToFunction->getParamType(ArgPos)
2538 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002539 return;
2540 }
2541
2542 // Handle different return type.
Alp Toker314cc812014-01-25 16:55:45 +00002543 if (!Context.hasSameType(FromFunction->getReturnType(),
2544 ToFunction->getReturnType())) {
2545 PDiag << ft_return_type << ToFunction->getReturnType()
2546 << FromFunction->getReturnType();
Richard Trieucaff2472011-11-23 22:32:32 +00002547 return;
2548 }
2549
2550 unsigned FromQuals = FromFunction->getTypeQuals(),
2551 ToQuals = ToFunction->getTypeQuals();
2552 if (FromQuals != ToQuals) {
2553 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2554 return;
2555 }
2556
2557 // Unable to find a difference, so add no extra info.
2558 PDiag << ft_default;
2559}
2560
Alp Toker9cacbab2014-01-20 20:26:09 +00002561/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002562/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002563/// they have same number of arguments. If the parameters are different,
2564/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002565bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2566 const FunctionProtoType *NewType,
2567 unsigned *ArgPos) {
2568 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2569 N = NewType->param_type_begin(),
2570 E = OldType->param_type_end();
2571 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002572 if (!Context.hasSameType(O->getUnqualifiedType(),
2573 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002574 if (ArgPos)
2575 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002576 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002577 }
2578 }
2579 return true;
2580}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002581
Douglas Gregor39c16d42008-10-24 04:54:22 +00002582/// CheckPointerConversion - Check the pointer conversion from the
2583/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002584/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002585/// conversions for which IsPointerConversion has already returned
2586/// true. It returns true and produces a diagnostic if there was an
2587/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002588bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002589 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002590 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002591 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002592 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002593 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002594
John McCall8cb679e2010-11-15 09:13:47 +00002595 Kind = CK_BitCast;
2596
David Blaikie1c7c8f72012-08-08 17:33:31 +00002597 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
Argyrios Kyrtzidis3e3305d2014-02-02 05:26:43 +00002598 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
David Blaikie1c7c8f72012-08-08 17:33:31 +00002599 Expr::NPCK_ZeroExpression) {
2600 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2601 DiagRuntimeBehavior(From->getExprLoc(), From,
2602 PDiag(diag::warn_impcast_bool_to_null_pointer)
2603 << ToType << From->getSourceRange());
2604 else if (!isUnevaluatedContext())
2605 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2606 << ToType << From->getSourceRange();
2607 }
John McCall9320b872011-09-09 05:25:32 +00002608 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2609 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002610 QualType FromPointeeType = FromPtrType->getPointeeType(),
2611 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002612
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002613 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2614 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002615 // We must have a derived-to-base conversion. Check an
2616 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002617 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2618 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002619 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002620 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002621 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002622
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002623 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002624 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002625 }
2626 }
John McCall9320b872011-09-09 05:25:32 +00002627 } else if (const ObjCObjectPointerType *ToPtrType =
2628 ToType->getAs<ObjCObjectPointerType>()) {
2629 if (const ObjCObjectPointerType *FromPtrType =
2630 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002631 // Objective-C++ conversions are always okay.
2632 // FIXME: We should have a different class of conversions for the
2633 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002634 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002635 return false;
John McCall9320b872011-09-09 05:25:32 +00002636 } else if (FromType->isBlockPointerType()) {
2637 Kind = CK_BlockPointerToObjCPointerCast;
2638 } else {
2639 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002640 }
John McCall9320b872011-09-09 05:25:32 +00002641 } else if (ToType->isBlockPointerType()) {
2642 if (!FromType->isBlockPointerType())
2643 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002644 }
John McCall8cb679e2010-11-15 09:13:47 +00002645
2646 // We shouldn't fall into this case unless it's valid for other
2647 // reasons.
2648 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2649 Kind = CK_NullToPointer;
2650
Douglas Gregor39c16d42008-10-24 04:54:22 +00002651 return false;
2652}
2653
Sebastian Redl72b597d2009-01-25 19:43:20 +00002654/// IsMemberPointerConversion - Determines whether the conversion of the
2655/// expression From, which has the (possibly adjusted) type FromType, can be
2656/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2657/// If so, returns true and places the converted type (that might differ from
2658/// ToType in its cv-qualifiers at some level) into ConvertedType.
2659bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002660 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002661 bool InOverloadResolution,
2662 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002663 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002664 if (!ToTypePtr)
2665 return false;
2666
2667 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002668 if (From->isNullPointerConstant(Context,
2669 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2670 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002671 ConvertedType = ToType;
2672 return true;
2673 }
2674
2675 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002676 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002677 if (!FromTypePtr)
2678 return false;
2679
2680 // A pointer to member of B can be converted to a pointer to member of D,
2681 // where D is derived from B (C++ 4.11p2).
2682 QualType FromClass(FromTypePtr->getClass(), 0);
2683 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002684
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002685 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002686 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002687 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002688 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2689 ToClass.getTypePtr());
2690 return true;
2691 }
2692
2693 return false;
2694}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002695
Sebastian Redl72b597d2009-01-25 19:43:20 +00002696/// CheckMemberPointerConversion - Check the member pointer conversion from the
2697/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002698/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002699/// for which IsMemberPointerConversion has already returned true. It returns
2700/// true and produces a diagnostic if there was an error, or returns false
2701/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002702bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002703 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002704 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002705 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002706 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002707 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002708 if (!FromPtrType) {
2709 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002710 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002711 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002712 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002713 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002714 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002715 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002716
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002717 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002718 assert(ToPtrType && "No member pointer cast has a target type "
2719 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002720
Sebastian Redled8f2002009-01-28 18:33:18 +00002721 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2722 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002723
Sebastian Redled8f2002009-01-28 18:33:18 +00002724 // FIXME: What about dependent types?
2725 assert(FromClass->isRecordType() && "Pointer into non-class.");
2726 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002727
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002728 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002729 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002730 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2731 assert(DerivationOkay &&
2732 "Should not have been called if derivation isn't OK.");
2733 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002734
Sebastian Redled8f2002009-01-28 18:33:18 +00002735 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2736 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002737 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2738 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2739 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2740 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002741 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002742
Douglas Gregor89ee6822009-02-28 01:32:25 +00002743 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002744 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2745 << FromClass << ToClass << QualType(VBase, 0)
2746 << From->getSourceRange();
2747 return true;
2748 }
2749
John McCall5b0829a2010-02-10 09:31:12 +00002750 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002751 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2752 Paths.front(),
2753 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002754
Anders Carlssond7923c62009-08-22 23:33:40 +00002755 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002756 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002757 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002758 return false;
2759}
2760
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002761/// Determine whether the lifetime conversion between the two given
2762/// qualifiers sets is nontrivial.
2763static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2764 Qualifiers ToQuals) {
2765 // Converting anything to const __unsafe_unretained is trivial.
2766 if (ToQuals.hasConst() &&
2767 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2768 return false;
2769
2770 return true;
2771}
2772
Douglas Gregor9a657932008-10-21 23:43:52 +00002773/// IsQualificationConversion - Determines whether the conversion from
2774/// an rvalue of type FromType to ToType is a qualification conversion
2775/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002776///
2777/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2778/// when the qualification conversion involves a change in the Objective-C
2779/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002780bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002781Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002782 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002783 FromType = Context.getCanonicalType(FromType);
2784 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002785 ObjCLifetimeConversion = false;
2786
Douglas Gregor9a657932008-10-21 23:43:52 +00002787 // If FromType and ToType are the same type, this is not a
2788 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002789 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002790 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002791
Douglas Gregor9a657932008-10-21 23:43:52 +00002792 // (C++ 4.4p4):
2793 // A conversion can add cv-qualifiers at levels other than the first
2794 // in multi-level pointers, subject to the following rules: [...]
2795 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002796 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002797 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002798 // Within each iteration of the loop, we check the qualifiers to
2799 // determine if this still looks like a qualification
2800 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002801 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002802 // until there are no more pointers or pointers-to-members left to
2803 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002804 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002805
Douglas Gregor90609aa2011-04-25 18:40:17 +00002806 Qualifiers FromQuals = FromType.getQualifiers();
2807 Qualifiers ToQuals = ToType.getQualifiers();
2808
John McCall31168b02011-06-15 23:02:42 +00002809 // Objective-C ARC:
2810 // Check Objective-C lifetime conversions.
2811 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2812 UnwrappedAnyPointer) {
2813 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002814 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2815 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00002816 FromQuals.removeObjCLifetime();
2817 ToQuals.removeObjCLifetime();
2818 } else {
2819 // Qualification conversions cannot cast between different
2820 // Objective-C lifetime qualifiers.
2821 return false;
2822 }
2823 }
2824
Douglas Gregorf30053d2011-05-08 06:09:53 +00002825 // Allow addition/removal of GC attributes but not changing GC attributes.
2826 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2827 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2828 FromQuals.removeObjCGCAttr();
2829 ToQuals.removeObjCGCAttr();
2830 }
2831
Douglas Gregor9a657932008-10-21 23:43:52 +00002832 // -- for every j > 0, if const is in cv 1,j then const is in cv
2833 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002834 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002835 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002836
Douglas Gregor9a657932008-10-21 23:43:52 +00002837 // -- if the cv 1,j and cv 2,j are different, then const is in
2838 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002839 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002840 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002841 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002842
Douglas Gregor9a657932008-10-21 23:43:52 +00002843 // Keep track of whether all prior cv-qualifiers in the "to" type
2844 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002845 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002846 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002847 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002848
2849 // We are left with FromType and ToType being the pointee types
2850 // after unwrapping the original FromType and ToType the same number
2851 // of types. If we unwrapped any pointers, and if FromType and
2852 // ToType have the same unqualified type (since we checked
2853 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002854 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002855}
2856
Douglas Gregorc79862f2012-04-12 17:51:55 +00002857/// \brief - Determine whether this is a conversion from a scalar type to an
2858/// atomic type.
2859///
2860/// If successful, updates \c SCS's second and third steps in the conversion
2861/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00002862static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2863 bool InOverloadResolution,
2864 StandardConversionSequence &SCS,
2865 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00002866 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2867 if (!ToAtomic)
2868 return false;
2869
2870 StandardConversionSequence InnerSCS;
2871 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2872 InOverloadResolution, InnerSCS,
2873 CStyle, /*AllowObjCWritebackConversion=*/false))
2874 return false;
2875
2876 SCS.Second = InnerSCS.Second;
2877 SCS.setToType(1, InnerSCS.getToType(1));
2878 SCS.Third = InnerSCS.Third;
2879 SCS.QualificationIncludesObjCLifetime
2880 = InnerSCS.QualificationIncludesObjCLifetime;
2881 SCS.setToType(2, InnerSCS.getToType(2));
2882 return true;
2883}
2884
Sebastian Redle5417162012-03-27 18:33:03 +00002885static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2886 CXXConstructorDecl *Constructor,
2887 QualType Type) {
2888 const FunctionProtoType *CtorType =
2889 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002890 if (CtorType->getNumParams() > 0) {
2891 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00002892 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2893 return true;
2894 }
2895 return false;
2896}
2897
Sebastian Redl82ace982012-02-11 23:51:08 +00002898static OverloadingResult
2899IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2900 CXXRecordDecl *To,
2901 UserDefinedConversionSequence &User,
2902 OverloadCandidateSet &CandidateSet,
2903 bool AllowExplicit) {
David Blaikieff7d47a2012-12-19 00:45:41 +00002904 DeclContext::lookup_result R = S.LookupConstructors(To);
2905 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl82ace982012-02-11 23:51:08 +00002906 Con != ConEnd; ++Con) {
2907 NamedDecl *D = *Con;
2908 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2909
2910 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00002911 CXXConstructorDecl *Constructor = nullptr;
Sebastian Redl82ace982012-02-11 23:51:08 +00002912 FunctionTemplateDecl *ConstructorTmpl
2913 = dyn_cast<FunctionTemplateDecl>(D);
2914 if (ConstructorTmpl)
2915 Constructor
2916 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2917 else
2918 Constructor = cast<CXXConstructorDecl>(D);
2919
2920 bool Usable = !Constructor->isInvalidDecl() &&
2921 S.isInitListConstructor(Constructor) &&
2922 (AllowExplicit || !Constructor->isExplicit());
2923 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00002924 // If the first argument is (a reference to) the target type,
2925 // suppress conversions.
2926 bool SuppressUserConversions =
2927 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl82ace982012-02-11 23:51:08 +00002928 if (ConstructorTmpl)
2929 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00002930 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002931 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002932 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002933 else
2934 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002935 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002936 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002937 }
2938 }
2939
2940 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2941
2942 OverloadCandidateSet::iterator Best;
2943 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2944 case OR_Success: {
2945 // Record the standard conversion we used and the conversion function.
2946 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00002947 QualType ThisType = Constructor->getThisType(S.Context);
2948 // Initializer lists don't have conversions as such.
2949 User.Before.setAsIdentityConversion();
2950 User.HadMultipleCandidates = HadMultipleCandidates;
2951 User.ConversionFunction = Constructor;
2952 User.FoundConversionFunction = Best->FoundDecl;
2953 User.After.setAsIdentityConversion();
2954 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2955 User.After.setAllToTypes(ToType);
2956 return OR_Success;
2957 }
2958
2959 case OR_No_Viable_Function:
2960 return OR_No_Viable_Function;
2961 case OR_Deleted:
2962 return OR_Deleted;
2963 case OR_Ambiguous:
2964 return OR_Ambiguous;
2965 }
2966
2967 llvm_unreachable("Invalid OverloadResult!");
2968}
2969
Douglas Gregor576e98c2009-01-30 23:27:23 +00002970/// Determines whether there is a user-defined conversion sequence
2971/// (C++ [over.ics.user]) that converts expression From to the type
2972/// ToType. If such a conversion exists, User will contain the
2973/// user-defined conversion sequence that performs such a conversion
2974/// and this routine will return true. Otherwise, this routine returns
2975/// false and User is unspecified.
2976///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002977/// \param AllowExplicit true if the conversion should consider C++0x
2978/// "explicit" conversion functions as well as non-explicit conversion
2979/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00002980///
2981/// \param AllowObjCConversionOnExplicit true if the conversion should
2982/// allow an extra Objective-C pointer conversion on uses of explicit
2983/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00002984static OverloadingResult
2985IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00002986 UserDefinedConversionSequence &User,
2987 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00002988 bool AllowExplicit,
2989 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00002990 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor4b60a152013-11-07 22:34:54 +00002991
Douglas Gregor5ab11652010-04-17 22:01:05 +00002992 // Whether we will only visit constructors.
2993 bool ConstructorsOnly = false;
2994
2995 // If the type we are conversion to is a class type, enumerate its
2996 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002997 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002998 // C++ [over.match.ctor]p1:
2999 // When objects of class type are direct-initialized (8.5), or
3000 // copy-initialized from an expression of the same or a
3001 // derived class type (8.5), overload resolution selects the
3002 // constructor. [...] For copy-initialization, the candidate
3003 // functions are all the converting constructors (12.3.1) of
3004 // that class. The argument list is the expression-list within
3005 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003006 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003007 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00003008 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003009 ConstructorsOnly = true;
3010
Benjamin Kramer90633e32012-11-23 17:04:52 +00003011 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00003012 // RequireCompleteType may have returned true due to some invalid decl
3013 // during template instantiation, but ToType may be complete enough now
3014 // to try to recover.
3015 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003016 // We're not going to find any constructors.
3017 } else if (CXXRecordDecl *ToRecordDecl
3018 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003019
3020 Expr **Args = &From;
3021 unsigned NumArgs = 1;
3022 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003023 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003024 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003025 OverloadingResult Result = IsInitializerListConstructorConversion(
3026 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3027 if (Result != OR_No_Viable_Function)
3028 return Result;
3029 // Never mind.
3030 CandidateSet.clear();
3031
3032 // If we're list-initializing, we pass the individual elements as
3033 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003034 Args = InitList->getInits();
3035 NumArgs = InitList->getNumInits();
3036 ListInitializing = true;
3037 }
3038
David Blaikieff7d47a2012-12-19 00:45:41 +00003039 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3040 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregor89ee6822009-02-28 01:32:25 +00003041 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003042 NamedDecl *D = *Con;
3043 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3044
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003045 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003046 CXXConstructorDecl *Constructor = nullptr;
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003047 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00003048 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003049 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003050 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003051 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3052 else
John McCalla0296f72010-03-19 07:35:19 +00003053 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003054
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003055 bool Usable = !Constructor->isInvalidDecl();
3056 if (ListInitializing)
3057 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3058 else
3059 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3060 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003061 bool SuppressUserConversions = !ConstructorsOnly;
3062 if (SuppressUserConversions && ListInitializing) {
3063 SuppressUserConversions = false;
3064 if (NumArgs == 1) {
3065 // If the first argument is (a reference to) the target type,
3066 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003067 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3068 S.Context, Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003069 }
3070 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003071 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00003072 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003073 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003074 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003075 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003076 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003077 // Allow one user-defined conversion when user specifies a
3078 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00003079 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003080 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003081 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003082 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003083 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003084 }
3085 }
3086
Douglas Gregor5ab11652010-04-17 22:01:05 +00003087 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003088 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003089 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003090 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003091 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003092 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003093 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003094 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3095 // Add all of the conversion functions as candidates.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00003096 std::pair<CXXRecordDecl::conversion_iterator,
3097 CXXRecordDecl::conversion_iterator>
3098 Conversions = FromRecordDecl->getVisibleConversionFunctions();
3099 for (CXXRecordDecl::conversion_iterator
3100 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003101 DeclAccessPair FoundDecl = I.getPair();
3102 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003103 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3104 if (isa<UsingShadowDecl>(D))
3105 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3106
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003107 CXXConversionDecl *Conv;
3108 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003109 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3110 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003111 else
John McCallda4458e2010-03-31 01:36:47 +00003112 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003113
3114 if (AllowExplicit || !Conv->isExplicit()) {
3115 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003116 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3117 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003118 CandidateSet,
3119 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003120 else
John McCall5c32be02010-08-24 20:38:10 +00003121 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003122 From, ToType, CandidateSet,
3123 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003124 }
3125 }
3126 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003127 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003128
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003129 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3130
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003131 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003132 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003133 case OR_Success:
3134 // Record the standard conversion we used and the conversion function.
3135 if (CXXConstructorDecl *Constructor
3136 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3137 // C++ [over.ics.user]p1:
3138 // If the user-defined conversion is specified by a
3139 // constructor (12.3.1), the initial standard conversion
3140 // sequence converts the source type to the type required by
3141 // the argument of the constructor.
3142 //
3143 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003144 if (isa<InitListExpr>(From)) {
3145 // Initializer lists don't have conversions as such.
3146 User.Before.setAsIdentityConversion();
3147 } else {
3148 if (Best->Conversions[0].isEllipsis())
3149 User.EllipsisConversion = true;
3150 else {
3151 User.Before = Best->Conversions[0].Standard;
3152 User.EllipsisConversion = false;
3153 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003154 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003155 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003156 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003157 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003158 User.After.setAsIdentityConversion();
3159 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3160 User.After.setAllToTypes(ToType);
3161 return OR_Success;
David Blaikie8a40f702012-01-17 06:56:22 +00003162 }
3163 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003164 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3165 // C++ [over.ics.user]p1:
3166 //
3167 // [...] If the user-defined conversion is specified by a
3168 // conversion function (12.3.2), the initial standard
3169 // conversion sequence converts the source type to the
3170 // implicit object parameter of the conversion function.
3171 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003172 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003173 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003174 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003175 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003176
John McCall5c32be02010-08-24 20:38:10 +00003177 // C++ [over.ics.user]p2:
3178 // The second standard conversion sequence converts the
3179 // result of the user-defined conversion to the target type
3180 // for the sequence. Since an implicit conversion sequence
3181 // is an initialization, the special rules for
3182 // initialization by user-defined conversion apply when
3183 // selecting the best user-defined conversion for a
3184 // user-defined conversion sequence (see 13.3.3 and
3185 // 13.3.3.1).
3186 User.After = Best->FinalConversion;
3187 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003188 }
David Blaikie8a40f702012-01-17 06:56:22 +00003189 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003190
John McCall5c32be02010-08-24 20:38:10 +00003191 case OR_No_Viable_Function:
3192 return OR_No_Viable_Function;
3193 case OR_Deleted:
3194 // No conversion here! We're done.
3195 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003196
John McCall5c32be02010-08-24 20:38:10 +00003197 case OR_Ambiguous:
3198 return OR_Ambiguous;
3199 }
3200
David Blaikie8a40f702012-01-17 06:56:22 +00003201 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003202}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003203
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003204bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003205Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003206 ImplicitConversionSequence ICS;
Richard Smith100b24a2014-04-17 01:52:14 +00003207 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3208 OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003209 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003210 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003211 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003212 if (OvResult == OR_Ambiguous)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003213 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3214 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003215 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003216 if (!RequireCompleteType(From->getLocStart(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003217 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003218 From->getType(), From->getSourceRange()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003219 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3220 << From->getType() << From->getSourceRange() << ToType;
3221 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003222 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003223 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003224 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003225}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003226
Douglas Gregor2837aa22012-02-22 17:32:19 +00003227/// \brief Compare the user-defined conversion functions or constructors
3228/// of two user-defined conversion sequences to determine whether any ordering
3229/// is possible.
3230static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003231compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003232 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003233 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003234 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003235
Douglas Gregor2837aa22012-02-22 17:32:19 +00003236 // Objective-C++:
3237 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003238 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003239 // respectively, always prefer the conversion to a function pointer,
3240 // because the function pointer is more lightweight and is more likely
3241 // to keep code working.
Ted Kremenek8d265c22014-04-01 07:23:18 +00003242 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003243 if (!Conv1)
3244 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003245
Douglas Gregor2837aa22012-02-22 17:32:19 +00003246 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3247 if (!Conv2)
3248 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003249
Douglas Gregor2837aa22012-02-22 17:32:19 +00003250 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3251 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3252 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3253 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003254 return Block1 ? ImplicitConversionSequence::Worse
3255 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003256 }
3257
3258 return ImplicitConversionSequence::Indistinguishable;
3259}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003260
3261static bool hasDeprecatedStringLiteralToCharPtrConversion(
3262 const ImplicitConversionSequence &ICS) {
3263 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3264 (ICS.isUserDefined() &&
3265 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3266}
3267
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003268/// CompareImplicitConversionSequences - Compare two implicit
3269/// conversion sequences to determine whether one is better than the
3270/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003271static ImplicitConversionSequence::CompareKind
3272CompareImplicitConversionSequences(Sema &S,
3273 const ImplicitConversionSequence& ICS1,
3274 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003275{
3276 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3277 // conversion sequences (as defined in 13.3.3.1)
3278 // -- a standard conversion sequence (13.3.3.1.1) is a better
3279 // conversion sequence than a user-defined conversion sequence or
3280 // an ellipsis conversion sequence, and
3281 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3282 // conversion sequence than an ellipsis conversion sequence
3283 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003284 //
John McCall0d1da222010-01-12 00:44:57 +00003285 // C++0x [over.best.ics]p10:
3286 // For the purpose of ranking implicit conversion sequences as
3287 // described in 13.3.3.2, the ambiguous conversion sequence is
3288 // treated as a user-defined sequence that is indistinguishable
3289 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003290
3291 // String literal to 'char *' conversion has been deprecated in C++03. It has
3292 // been removed from C++11. We still accept this conversion, if it happens at
3293 // the best viable function. Otherwise, this conversion is considered worse
3294 // than ellipsis conversion. Consider this as an extension; this is not in the
3295 // standard. For example:
3296 //
3297 // int &f(...); // #1
3298 // void f(char*); // #2
3299 // void g() { int &r = f("foo"); }
3300 //
3301 // In C++03, we pick #2 as the best viable function.
3302 // In C++11, we pick #1 as the best viable function, because ellipsis
3303 // conversion is better than string-literal to char* conversion (since there
3304 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3305 // convert arguments, #2 would be the best viable function in C++11.
3306 // If the best viable function has this conversion, a warning will be issued
3307 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3308
3309 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3310 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3311 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3312 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3313 ? ImplicitConversionSequence::Worse
3314 : ImplicitConversionSequence::Better;
3315
Douglas Gregor5ab11652010-04-17 22:01:05 +00003316 if (ICS1.getKindRank() < ICS2.getKindRank())
3317 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003318 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003319 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003320
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003321 // The following checks require both conversion sequences to be of
3322 // the same kind.
3323 if (ICS1.getKind() != ICS2.getKind())
3324 return ImplicitConversionSequence::Indistinguishable;
3325
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003326 ImplicitConversionSequence::CompareKind Result =
3327 ImplicitConversionSequence::Indistinguishable;
3328
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003329 // Two implicit conversion sequences of the same form are
3330 // indistinguishable conversion sequences unless one of the
3331 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00003332 if (ICS1.isStandard())
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003333 Result = CompareStandardConversionSequences(S,
3334 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003335 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003336 // User-defined conversion sequence U1 is a better conversion
3337 // sequence than another user-defined conversion sequence U2 if
3338 // they contain the same user-defined conversion function or
3339 // constructor and if the second standard conversion sequence of
3340 // U1 is better than the second standard conversion sequence of
3341 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003342 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003343 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003344 Result = CompareStandardConversionSequences(S,
3345 ICS1.UserDefined.After,
3346 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003347 else
3348 Result = compareConversionFunctions(S,
3349 ICS1.UserDefined.ConversionFunction,
3350 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003351 }
3352
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003353 // List-initialization sequence L1 is a better conversion sequence than
3354 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3355 // for some X and L2 does not.
3356 if (Result == ImplicitConversionSequence::Indistinguishable &&
Richard Smitha93f1022013-09-06 22:30:28 +00003357 !ICS1.isBad()) {
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00003358 if (ICS1.isStdInitializerListElement() &&
3359 !ICS2.isStdInitializerListElement())
3360 return ImplicitConversionSequence::Better;
3361 if (!ICS1.isStdInitializerListElement() &&
3362 ICS2.isStdInitializerListElement())
3363 return ImplicitConversionSequence::Worse;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003364 }
3365
3366 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003367}
3368
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003369static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3370 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3371 Qualifiers Quals;
3372 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003373 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003374 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003375
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003376 return Context.hasSameUnqualifiedType(T1, T2);
3377}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003378
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003379// Per 13.3.3.2p3, compare the given standard conversion sequences to
3380// determine if one is a proper subset of the other.
3381static ImplicitConversionSequence::CompareKind
3382compareStandardConversionSubsets(ASTContext &Context,
3383 const StandardConversionSequence& SCS1,
3384 const StandardConversionSequence& SCS2) {
3385 ImplicitConversionSequence::CompareKind Result
3386 = ImplicitConversionSequence::Indistinguishable;
3387
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003388 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003389 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003390 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3391 return ImplicitConversionSequence::Better;
3392 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3393 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003394
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003395 if (SCS1.Second != SCS2.Second) {
3396 if (SCS1.Second == ICK_Identity)
3397 Result = ImplicitConversionSequence::Better;
3398 else if (SCS2.Second == ICK_Identity)
3399 Result = ImplicitConversionSequence::Worse;
3400 else
3401 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003402 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003403 return ImplicitConversionSequence::Indistinguishable;
3404
3405 if (SCS1.Third == SCS2.Third) {
3406 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3407 : ImplicitConversionSequence::Indistinguishable;
3408 }
3409
3410 if (SCS1.Third == ICK_Identity)
3411 return Result == ImplicitConversionSequence::Worse
3412 ? ImplicitConversionSequence::Indistinguishable
3413 : ImplicitConversionSequence::Better;
3414
3415 if (SCS2.Third == ICK_Identity)
3416 return Result == ImplicitConversionSequence::Better
3417 ? ImplicitConversionSequence::Indistinguishable
3418 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003419
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003420 return ImplicitConversionSequence::Indistinguishable;
3421}
3422
Douglas Gregore696ebb2011-01-26 14:52:12 +00003423/// \brief Determine whether one of the given reference bindings is better
3424/// than the other based on what kind of bindings they are.
Richard Smith19172c42014-07-14 02:28:44 +00003425static bool
3426isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3427 const StandardConversionSequence &SCS2) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003428 // C++0x [over.ics.rank]p3b4:
3429 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3430 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003431 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003432 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003433 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003434 // reference*.
3435 //
3436 // FIXME: Rvalue references. We're going rogue with the above edits,
3437 // because the semantics in the current C++0x working paper (N3225 at the
3438 // time of this writing) break the standard definition of std::forward
3439 // and std::reference_wrapper when dealing with references to functions.
3440 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003441 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3442 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3443 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003444
Douglas Gregore696ebb2011-01-26 14:52:12 +00003445 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3446 SCS2.IsLvalueReference) ||
3447 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
Richard Smith19172c42014-07-14 02:28:44 +00003448 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
Douglas Gregore696ebb2011-01-26 14:52:12 +00003449}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003450
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003451/// CompareStandardConversionSequences - Compare two standard
3452/// conversion sequences to determine whether one is better than the
3453/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003454static ImplicitConversionSequence::CompareKind
3455CompareStandardConversionSequences(Sema &S,
3456 const StandardConversionSequence& SCS1,
3457 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003458{
3459 // Standard conversion sequence S1 is a better conversion sequence
3460 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3461
3462 // -- S1 is a proper subsequence of S2 (comparing the conversion
3463 // sequences in the canonical form defined by 13.3.3.1.1,
3464 // excluding any Lvalue Transformation; the identity conversion
3465 // sequence is considered to be a subsequence of any
3466 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003467 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003468 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003469 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003470
3471 // -- the rank of S1 is better than the rank of S2 (by the rules
3472 // defined below), or, if not that,
3473 ImplicitConversionRank Rank1 = SCS1.getRank();
3474 ImplicitConversionRank Rank2 = SCS2.getRank();
3475 if (Rank1 < Rank2)
3476 return ImplicitConversionSequence::Better;
3477 else if (Rank2 < Rank1)
3478 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003479
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003480 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3481 // are indistinguishable unless one of the following rules
3482 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003483
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003484 // A conversion that is not a conversion of a pointer, or
3485 // pointer to member, to bool is better than another conversion
3486 // that is such a conversion.
3487 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3488 return SCS2.isPointerConversionToBool()
3489 ? ImplicitConversionSequence::Better
3490 : ImplicitConversionSequence::Worse;
3491
Douglas Gregor5c407d92008-10-23 00:40:37 +00003492 // C++ [over.ics.rank]p4b2:
3493 //
3494 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003495 // conversion of B* to A* is better than conversion of B* to
3496 // void*, and conversion of A* to void* is better than conversion
3497 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003498 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003499 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003500 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003501 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003502 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3503 // Exactly one of the conversion sequences is a conversion to
3504 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003505 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3506 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003507 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3508 // Neither conversion sequence converts to a void pointer; compare
3509 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003510 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00003511 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003512 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003513 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3514 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003515 // Both conversion sequences are conversions to void
3516 // pointers. Compare the source types to determine if there's an
3517 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003518 QualType FromType1 = SCS1.getFromType();
3519 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003520
3521 // Adjust the types we're converting from via the array-to-pointer
3522 // conversion, if we need to.
3523 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003524 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003525 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003526 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003527
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003528 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3529 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003530
John McCall5c32be02010-08-24 20:38:10 +00003531 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003532 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003533 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003534 return ImplicitConversionSequence::Worse;
3535
3536 // Objective-C++: If one interface is more specific than the
3537 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003538 const ObjCObjectPointerType* FromObjCPtr1
3539 = FromType1->getAs<ObjCObjectPointerType>();
3540 const ObjCObjectPointerType* FromObjCPtr2
3541 = FromType2->getAs<ObjCObjectPointerType>();
3542 if (FromObjCPtr1 && FromObjCPtr2) {
3543 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3544 FromObjCPtr2);
3545 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3546 FromObjCPtr1);
3547 if (AssignLeft != AssignRight) {
3548 return AssignLeft? ImplicitConversionSequence::Better
3549 : ImplicitConversionSequence::Worse;
3550 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003551 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003552 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003553
3554 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3555 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003556 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003557 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003558 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003559
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003560 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003561 // Check for a better reference binding based on the kind of bindings.
3562 if (isBetterReferenceBindingKind(SCS1, SCS2))
3563 return ImplicitConversionSequence::Better;
3564 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3565 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003566
Sebastian Redlb28b4072009-03-22 23:49:27 +00003567 // C++ [over.ics.rank]p3b4:
3568 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3569 // which the references refer are the same type except for
3570 // top-level cv-qualifiers, and the type to which the reference
3571 // initialized by S2 refers is more cv-qualified than the type
3572 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003573 QualType T1 = SCS1.getToType(2);
3574 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003575 T1 = S.Context.getCanonicalType(T1);
3576 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003577 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003578 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3579 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003580 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003581 // Objective-C++ ARC: If the references refer to objects with different
3582 // lifetimes, prefer bindings that don't change lifetime.
3583 if (SCS1.ObjCLifetimeConversionBinding !=
3584 SCS2.ObjCLifetimeConversionBinding) {
3585 return SCS1.ObjCLifetimeConversionBinding
3586 ? ImplicitConversionSequence::Worse
3587 : ImplicitConversionSequence::Better;
3588 }
3589
Chandler Carruth8e543b32010-12-12 08:17:55 +00003590 // If the type is an array type, promote the element qualifiers to the
3591 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003592 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003593 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003594 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003595 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003596 if (T2.isMoreQualifiedThan(T1))
3597 return ImplicitConversionSequence::Better;
3598 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003599 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003600 }
3601 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003602
Francois Pichet08d2fa02011-09-18 21:37:37 +00003603 // In Microsoft mode, prefer an integral conversion to a
3604 // floating-to-integral conversion if the integral conversion
3605 // is between types of the same size.
3606 // For example:
3607 // void f(float);
3608 // void f(int);
3609 // int main {
3610 // long a;
3611 // f(a);
3612 // }
3613 // Here, MSVC will call f(int) instead of generating a compile error
3614 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003615 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3616 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003617 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003618 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003619 return ImplicitConversionSequence::Better;
3620
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003621 return ImplicitConversionSequence::Indistinguishable;
3622}
3623
3624/// CompareQualificationConversions - Compares two standard conversion
3625/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003626/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
Richard Smith17c00b42014-11-12 01:24:00 +00003627static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003628CompareQualificationConversions(Sema &S,
3629 const StandardConversionSequence& SCS1,
3630 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003631 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003632 // -- S1 and S2 differ only in their qualification conversion and
3633 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3634 // cv-qualification signature of type T1 is a proper subset of
3635 // the cv-qualification signature of type T2, and S1 is not the
3636 // deprecated string literal array-to-pointer conversion (4.2).
3637 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3638 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3639 return ImplicitConversionSequence::Indistinguishable;
3640
3641 // FIXME: the example in the standard doesn't use a qualification
3642 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003643 QualType T1 = SCS1.getToType(2);
3644 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003645 T1 = S.Context.getCanonicalType(T1);
3646 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003647 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003648 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3649 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003650
3651 // If the types are the same, we won't learn anything by unwrapped
3652 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003653 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003654 return ImplicitConversionSequence::Indistinguishable;
3655
Chandler Carruth607f38e2009-12-29 07:16:59 +00003656 // If the type is an array type, promote the element qualifiers to the type
3657 // for comparison.
3658 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003659 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003660 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003661 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003662
Mike Stump11289f42009-09-09 15:08:12 +00003663 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003664 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003665
3666 // Objective-C++ ARC:
3667 // Prefer qualification conversions not involving a change in lifetime
3668 // to qualification conversions that do not change lifetime.
3669 if (SCS1.QualificationIncludesObjCLifetime !=
3670 SCS2.QualificationIncludesObjCLifetime) {
3671 Result = SCS1.QualificationIncludesObjCLifetime
3672 ? ImplicitConversionSequence::Worse
3673 : ImplicitConversionSequence::Better;
3674 }
3675
John McCall5c32be02010-08-24 20:38:10 +00003676 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003677 // Within each iteration of the loop, we check the qualifiers to
3678 // determine if this still looks like a qualification
3679 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003680 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003681 // until there are no more pointers or pointers-to-members left
3682 // to unwrap. This essentially mimics what
3683 // IsQualificationConversion does, but here we're checking for a
3684 // strict subset of qualifiers.
3685 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3686 // The qualifiers are the same, so this doesn't tell us anything
3687 // about how the sequences rank.
3688 ;
3689 else if (T2.isMoreQualifiedThan(T1)) {
3690 // T1 has fewer qualifiers, so it could be the better sequence.
3691 if (Result == ImplicitConversionSequence::Worse)
3692 // Neither has qualifiers that are a subset of the other's
3693 // qualifiers.
3694 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003695
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003696 Result = ImplicitConversionSequence::Better;
3697 } else if (T1.isMoreQualifiedThan(T2)) {
3698 // T2 has fewer qualifiers, so it could be the better sequence.
3699 if (Result == ImplicitConversionSequence::Better)
3700 // Neither has qualifiers that are a subset of the other's
3701 // qualifiers.
3702 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003703
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003704 Result = ImplicitConversionSequence::Worse;
3705 } else {
3706 // Qualifiers are disjoint.
3707 return ImplicitConversionSequence::Indistinguishable;
3708 }
3709
3710 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003711 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003712 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003713 }
3714
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003715 // Check that the winning standard conversion sequence isn't using
3716 // the deprecated string literal array to pointer conversion.
3717 switch (Result) {
3718 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003719 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003720 Result = ImplicitConversionSequence::Indistinguishable;
3721 break;
3722
3723 case ImplicitConversionSequence::Indistinguishable:
3724 break;
3725
3726 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003727 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003728 Result = ImplicitConversionSequence::Indistinguishable;
3729 break;
3730 }
3731
3732 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003733}
3734
Douglas Gregor5c407d92008-10-23 00:40:37 +00003735/// CompareDerivedToBaseConversions - Compares two standard conversion
3736/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003737/// various kinds of derived-to-base conversions (C++
3738/// [over.ics.rank]p4b3). As part of these checks, we also look at
3739/// conversions between Objective-C interface types.
Richard Smith17c00b42014-11-12 01:24:00 +00003740static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003741CompareDerivedToBaseConversions(Sema &S,
3742 const StandardConversionSequence& SCS1,
3743 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003744 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003745 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003746 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003747 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003748
3749 // Adjust the types we're converting from via the array-to-pointer
3750 // conversion, if we need to.
3751 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003752 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003753 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003754 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003755
3756 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003757 FromType1 = S.Context.getCanonicalType(FromType1);
3758 ToType1 = S.Context.getCanonicalType(ToType1);
3759 FromType2 = S.Context.getCanonicalType(FromType2);
3760 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003761
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003762 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003763 //
3764 // If class B is derived directly or indirectly from class A and
3765 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003766 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003767 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003768 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003769 SCS2.Second == ICK_Pointer_Conversion &&
3770 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3771 FromType1->isPointerType() && FromType2->isPointerType() &&
3772 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003773 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003774 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003775 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003776 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003777 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003778 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003779 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003780 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003781
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003782 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003783 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003784 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003785 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003786 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003787 return ImplicitConversionSequence::Worse;
3788 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003789
3790 // -- conversion of B* to A* is better than conversion of C* to A*,
3791 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003792 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003793 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003794 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003795 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003796 }
3797 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3798 SCS2.Second == ICK_Pointer_Conversion) {
3799 const ObjCObjectPointerType *FromPtr1
3800 = FromType1->getAs<ObjCObjectPointerType>();
3801 const ObjCObjectPointerType *FromPtr2
3802 = FromType2->getAs<ObjCObjectPointerType>();
3803 const ObjCObjectPointerType *ToPtr1
3804 = ToType1->getAs<ObjCObjectPointerType>();
3805 const ObjCObjectPointerType *ToPtr2
3806 = ToType2->getAs<ObjCObjectPointerType>();
3807
3808 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3809 // Apply the same conversion ranking rules for Objective-C pointer types
3810 // that we do for C++ pointers to class types. However, we employ the
3811 // Objective-C pseudo-subtyping relationship used for assignment of
3812 // Objective-C pointer types.
3813 bool FromAssignLeft
3814 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3815 bool FromAssignRight
3816 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3817 bool ToAssignLeft
3818 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3819 bool ToAssignRight
3820 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3821
3822 // A conversion to an a non-id object pointer type or qualified 'id'
3823 // type is better than a conversion to 'id'.
3824 if (ToPtr1->isObjCIdType() &&
3825 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3826 return ImplicitConversionSequence::Worse;
3827 if (ToPtr2->isObjCIdType() &&
3828 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3829 return ImplicitConversionSequence::Better;
3830
3831 // A conversion to a non-id object pointer type is better than a
3832 // conversion to a qualified 'id' type
3833 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3834 return ImplicitConversionSequence::Worse;
3835 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3836 return ImplicitConversionSequence::Better;
3837
3838 // A conversion to an a non-Class object pointer type or qualified 'Class'
3839 // type is better than a conversion to 'Class'.
3840 if (ToPtr1->isObjCClassType() &&
3841 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3842 return ImplicitConversionSequence::Worse;
3843 if (ToPtr2->isObjCClassType() &&
3844 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3845 return ImplicitConversionSequence::Better;
3846
3847 // A conversion to a non-Class object pointer type is better than a
3848 // conversion to a qualified 'Class' type.
3849 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3850 return ImplicitConversionSequence::Worse;
3851 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3852 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003853
Douglas Gregor058d3de2011-01-31 18:51:41 +00003854 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3855 if (S.Context.hasSameType(FromType1, FromType2) &&
3856 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3857 (ToAssignLeft != ToAssignRight))
3858 return ToAssignLeft? ImplicitConversionSequence::Worse
3859 : ImplicitConversionSequence::Better;
3860
3861 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3862 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3863 (FromAssignLeft != FromAssignRight))
3864 return FromAssignLeft? ImplicitConversionSequence::Better
3865 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003866 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003867 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003868
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003869 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003870 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3871 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3872 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003873 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003874 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003875 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003876 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003877 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003878 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003879 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003880 ToType2->getAs<MemberPointerType>();
3881 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3882 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3883 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3884 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3885 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3886 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3887 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3888 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003889 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003890 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003891 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003892 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003893 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003894 return ImplicitConversionSequence::Better;
3895 }
3896 // conversion of B::* to C::* is better than conversion of A::* to C::*
3897 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003898 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003899 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003900 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003901 return ImplicitConversionSequence::Worse;
3902 }
3903 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003904
Douglas Gregor5ab11652010-04-17 22:01:05 +00003905 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003906 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003907 // -- binding of an expression of type C to a reference of type
3908 // B& is better than binding an expression of type C to a
3909 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003910 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3911 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3912 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003913 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003914 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003915 return ImplicitConversionSequence::Worse;
3916 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003917
Douglas Gregor2fe98832008-11-03 19:09:14 +00003918 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003919 // -- binding of an expression of type B to a reference of type
3920 // A& is better than binding an expression of type C to a
3921 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003922 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3923 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3924 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003925 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003926 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003927 return ImplicitConversionSequence::Worse;
3928 }
3929 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003930
Douglas Gregor5c407d92008-10-23 00:40:37 +00003931 return ImplicitConversionSequence::Indistinguishable;
3932}
3933
Douglas Gregor45bb4832013-03-26 23:36:30 +00003934/// \brief Determine whether the given type is valid, e.g., it is not an invalid
3935/// C++ class.
3936static bool isTypeValid(QualType T) {
3937 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3938 return !Record->isInvalidDecl();
3939
3940 return true;
3941}
3942
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003943/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3944/// determine whether they are reference-related,
3945/// reference-compatible, reference-compatible with added
3946/// qualification, or incompatible, for use in C++ initialization by
3947/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3948/// type, and the first type (T1) is the pointee type of the reference
3949/// type being initialized.
3950Sema::ReferenceCompareResult
3951Sema::CompareReferenceRelationship(SourceLocation Loc,
3952 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003953 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003954 bool &ObjCConversion,
3955 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003956 assert(!OrigT1->isReferenceType() &&
3957 "T1 must be the pointee type of the reference type");
3958 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3959
3960 QualType T1 = Context.getCanonicalType(OrigT1);
3961 QualType T2 = Context.getCanonicalType(OrigT2);
3962 Qualifiers T1Quals, T2Quals;
3963 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3964 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3965
3966 // C++ [dcl.init.ref]p4:
3967 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3968 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3969 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003970 DerivedToBase = false;
3971 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003972 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003973 if (UnqualT1 == UnqualT2) {
3974 // Nothing to do.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003975 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00003976 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
3977 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003978 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003979 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3980 UnqualT2->isObjCObjectOrInterfaceType() &&
3981 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3982 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003983 else
3984 return Ref_Incompatible;
3985
3986 // At this point, we know that T1 and T2 are reference-related (at
3987 // least).
3988
3989 // If the type is an array type, promote the element qualifiers to the type
3990 // for comparison.
3991 if (isa<ArrayType>(T1) && T1Quals)
3992 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3993 if (isa<ArrayType>(T2) && T2Quals)
3994 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3995
3996 // C++ [dcl.init.ref]p4:
3997 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3998 // reference-related to T2 and cv1 is the same cv-qualification
3999 // as, or greater cv-qualification than, cv2. For purposes of
4000 // overload resolution, cases for which cv1 is greater
4001 // cv-qualification than cv2 are identified as
4002 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004003 //
4004 // Note that we also require equivalence of Objective-C GC and address-space
4005 // qualifiers when performing these computations, so that e.g., an int in
4006 // address space 1 is not reference-compatible with an int in address
4007 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004008 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4009 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004010 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4011 ObjCLifetimeConversion = true;
4012
John McCall31168b02011-06-15 23:02:42 +00004013 T1Quals.removeObjCLifetime();
4014 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004015 }
4016
Douglas Gregord517d552011-04-28 17:56:11 +00004017 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004018 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00004019 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004020 return Ref_Compatible_With_Added_Qualification;
4021 else
4022 return Ref_Related;
4023}
4024
Douglas Gregor836a7e82010-08-11 02:15:33 +00004025/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004026/// with DeclType. Return true if something definite is found.
4027static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004028FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4029 QualType DeclType, SourceLocation DeclLoc,
4030 Expr *Init, QualType T2, bool AllowRvalues,
4031 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004032 assert(T2->isRecordType() && "Can only find conversions of record types.");
4033 CXXRecordDecl *T2RecordDecl
4034 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4035
Richard Smith100b24a2014-04-17 01:52:14 +00004036 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00004037 std::pair<CXXRecordDecl::conversion_iterator,
4038 CXXRecordDecl::conversion_iterator>
4039 Conversions = T2RecordDecl->getVisibleConversionFunctions();
4040 for (CXXRecordDecl::conversion_iterator
4041 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004042 NamedDecl *D = *I;
4043 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4044 if (isa<UsingShadowDecl>(D))
4045 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4046
4047 FunctionTemplateDecl *ConvTemplate
4048 = dyn_cast<FunctionTemplateDecl>(D);
4049 CXXConversionDecl *Conv;
4050 if (ConvTemplate)
4051 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4052 else
4053 Conv = cast<CXXConversionDecl>(D);
4054
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004055 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004056 // explicit conversions, skip it.
4057 if (!AllowExplicit && Conv->isExplicit())
4058 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004059
Douglas Gregor836a7e82010-08-11 02:15:33 +00004060 if (AllowRvalues) {
4061 bool DerivedToBase = false;
4062 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004063 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004064
4065 // If we are initializing an rvalue reference, don't permit conversion
4066 // functions that return lvalues.
4067 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4068 const ReferenceType *RefType
4069 = Conv->getConversionType()->getAs<LValueReferenceType>();
4070 if (RefType && !RefType->getPointeeType()->isFunctionType())
4071 continue;
4072 }
4073
Douglas Gregor836a7e82010-08-11 02:15:33 +00004074 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004075 S.CompareReferenceRelationship(
4076 DeclLoc,
4077 Conv->getConversionType().getNonReferenceType()
4078 .getUnqualifiedType(),
4079 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004080 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004081 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004082 continue;
4083 } else {
4084 // If the conversion function doesn't return a reference type,
4085 // it can't be considered for this conversion. An rvalue reference
4086 // is only acceptable if its referencee is a function type.
4087
4088 const ReferenceType *RefType =
4089 Conv->getConversionType()->getAs<ReferenceType>();
4090 if (!RefType ||
4091 (!RefType->isLValueReferenceType() &&
4092 !RefType->getPointeeType()->isFunctionType()))
4093 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004094 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004095
Douglas Gregor836a7e82010-08-11 02:15:33 +00004096 if (ConvTemplate)
4097 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004098 Init, DeclType, CandidateSet,
4099 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004100 else
4101 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004102 DeclType, CandidateSet,
4103 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004104 }
4105
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004106 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4107
Sebastian Redld92badf2010-06-30 18:13:39 +00004108 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004109 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004110 case OR_Success:
4111 // C++ [over.ics.ref]p1:
4112 //
4113 // [...] If the parameter binds directly to the result of
4114 // applying a conversion function to the argument
4115 // expression, the implicit conversion sequence is a
4116 // user-defined conversion sequence (13.3.3.1.2), with the
4117 // second standard conversion sequence either an identity
4118 // conversion or, if the conversion function returns an
4119 // entity of a type that is a derived class of the parameter
4120 // type, a derived-to-base Conversion.
4121 if (!Best->FinalConversion.DirectBinding)
4122 return false;
4123
4124 ICS.setUserDefined();
4125 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4126 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004127 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004128 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004129 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004130 ICS.UserDefined.EllipsisConversion = false;
4131 assert(ICS.UserDefined.After.ReferenceBinding &&
4132 ICS.UserDefined.After.DirectBinding &&
4133 "Expected a direct reference binding!");
4134 return true;
4135
4136 case OR_Ambiguous:
4137 ICS.setAmbiguous();
4138 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4139 Cand != CandidateSet.end(); ++Cand)
4140 if (Cand->Viable)
4141 ICS.Ambiguous.addConversion(Cand->Function);
4142 return true;
4143
4144 case OR_No_Viable_Function:
4145 case OR_Deleted:
4146 // There was no suitable conversion, or we found a deleted
4147 // conversion; continue with other checks.
4148 return false;
4149 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004150
David Blaikie8a40f702012-01-17 06:56:22 +00004151 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004152}
4153
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004154/// \brief Compute an implicit conversion sequence for reference
4155/// initialization.
4156static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004157TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004158 SourceLocation DeclLoc,
4159 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004160 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004161 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4162
4163 // Most paths end in a failed conversion.
4164 ImplicitConversionSequence ICS;
4165 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4166
4167 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4168 QualType T2 = Init->getType();
4169
4170 // If the initializer is the address of an overloaded function, try
4171 // to resolve the overloaded function. If all goes well, T2 is the
4172 // type of the resulting function.
4173 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4174 DeclAccessPair Found;
4175 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4176 false, Found))
4177 T2 = Fn->getType();
4178 }
4179
4180 // Compute some basic properties of the types and the initializer.
4181 bool isRValRef = DeclType->isRValueReferenceType();
4182 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004183 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004184 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004185 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004186 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004187 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004188 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004189
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004190
Sebastian Redld92badf2010-06-30 18:13:39 +00004191 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004192 // A reference to type "cv1 T1" is initialized by an expression
4193 // of type "cv2 T2" as follows:
4194
Sebastian Redld92badf2010-06-30 18:13:39 +00004195 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004196 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004197 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4198 // reference-compatible with "cv2 T2," or
4199 //
4200 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4201 if (InitCategory.isLValue() &&
4202 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004203 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004204 // When a parameter of reference type binds directly (8.5.3)
4205 // to an argument expression, the implicit conversion sequence
4206 // is the identity conversion, unless the argument expression
4207 // has a type that is a derived class of the parameter type,
4208 // in which case the implicit conversion sequence is a
4209 // derived-to-base Conversion (13.3.3.1).
4210 ICS.setStandard();
4211 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004212 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4213 : ObjCConversion? ICK_Compatible_Conversion
4214 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004215 ICS.Standard.Third = ICK_Identity;
4216 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4217 ICS.Standard.setToType(0, T2);
4218 ICS.Standard.setToType(1, T1);
4219 ICS.Standard.setToType(2, T1);
4220 ICS.Standard.ReferenceBinding = true;
4221 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004222 ICS.Standard.IsLvalueReference = !isRValRef;
4223 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4224 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004225 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004226 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004227 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004228 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004229
Sebastian Redld92badf2010-06-30 18:13:39 +00004230 // Nothing more to do: the inaccessibility/ambiguity check for
4231 // derived-to-base conversions is suppressed when we're
4232 // computing the implicit conversion sequence (C++
4233 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004234 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004235 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004236
Sebastian Redld92badf2010-06-30 18:13:39 +00004237 // -- has a class type (i.e., T2 is a class type), where T1 is
4238 // not reference-related to T2, and can be implicitly
4239 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4240 // is reference-compatible with "cv3 T3" 92) (this
4241 // conversion is selected by enumerating the applicable
4242 // conversion functions (13.3.1.6) and choosing the best
4243 // one through overload resolution (13.3)),
4244 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004245 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004246 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004247 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4248 Init, T2, /*AllowRvalues=*/false,
4249 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004250 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004251 }
4252 }
4253
Sebastian Redld92badf2010-06-30 18:13:39 +00004254 // -- Otherwise, the reference shall be an lvalue reference to a
4255 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004256 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004257 //
Douglas Gregor870f3742010-04-18 09:22:00 +00004258 // We actually handle one oddity of C++ [over.ics.ref] at this
4259 // point, which is that, due to p2 (which short-circuits reference
4260 // binding by only attempting a simple conversion for non-direct
4261 // bindings) and p3's strange wording, we allow a const volatile
4262 // reference to bind to an rvalue. Hence the check for the presence
4263 // of "const" rather than checking for "const" being the only
4264 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00004265 // This is also the point where rvalue references and lvalue inits no longer
4266 // go together.
Richard Smithce4f6082012-05-24 04:29:20 +00004267 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004268 return ICS;
4269
Douglas Gregorf143cd52011-01-24 16:14:37 +00004270 // -- If the initializer expression
4271 //
4272 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004273 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004274 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4275 (InitCategory.isXValue() ||
4276 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4277 (InitCategory.isLValue() && T2->isFunctionType()))) {
4278 ICS.setStandard();
4279 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004280 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004281 : ObjCConversion? ICK_Compatible_Conversion
4282 : ICK_Identity;
4283 ICS.Standard.Third = ICK_Identity;
4284 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4285 ICS.Standard.setToType(0, T2);
4286 ICS.Standard.setToType(1, T1);
4287 ICS.Standard.setToType(2, T1);
4288 ICS.Standard.ReferenceBinding = true;
4289 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4290 // binding unless we're binding to a class prvalue.
4291 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4292 // allow the use of rvalue references in C++98/03 for the benefit of
4293 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004294 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004295 S.getLangOpts().CPlusPlus11 ||
Richard Smithb94afe12014-07-14 19:54:05 +00004296 !(InitCategory.isPRValue() || T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004297 ICS.Standard.IsLvalueReference = !isRValRef;
4298 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004299 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004300 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004301 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004302 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004303 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004304 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004305 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004306
Douglas Gregorf143cd52011-01-24 16:14:37 +00004307 // -- has a class type (i.e., T2 is a class type), where T1 is not
4308 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004309 // an xvalue, class prvalue, or function lvalue of type
4310 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004311 // "cv3 T3",
4312 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004313 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004314 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004315 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004316 // class subobject).
4317 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004318 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004319 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4320 Init, T2, /*AllowRvalues=*/true,
4321 AllowExplicit)) {
4322 // In the second case, if the reference is an rvalue reference
4323 // and the second standard conversion sequence of the
4324 // user-defined conversion sequence includes an lvalue-to-rvalue
4325 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004326 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004327 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4328 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4329
Douglas Gregor95273c32011-01-21 16:36:05 +00004330 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004331 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004332
Richard Smith19172c42014-07-14 02:28:44 +00004333 // A temporary of function type cannot be created; don't even try.
4334 if (T1->isFunctionType())
4335 return ICS;
4336
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004337 // -- Otherwise, a temporary of type "cv1 T1" is created and
4338 // initialized from the initializer expression using the
4339 // rules for a non-reference copy initialization (8.5). The
4340 // reference is then bound to the temporary. If T1 is
4341 // reference-related to T2, cv1 must be the same
4342 // cv-qualification as, or greater cv-qualification than,
4343 // cv2; otherwise, the program is ill-formed.
4344 if (RefRelationship == Sema::Ref_Related) {
4345 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4346 // we would be reference-compatible or reference-compatible with
4347 // added qualification. But that wasn't the case, so the reference
4348 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004349 //
4350 // Note that we only want to check address spaces and cvr-qualifiers here.
4351 // ObjC GC and lifetime qualifiers aren't important.
4352 Qualifiers T1Quals = T1.getQualifiers();
4353 Qualifiers T2Quals = T2.getQualifiers();
4354 T1Quals.removeObjCGCAttr();
4355 T1Quals.removeObjCLifetime();
4356 T2Quals.removeObjCGCAttr();
4357 T2Quals.removeObjCLifetime();
4358 if (!T1Quals.compatiblyIncludes(T2Quals))
4359 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004360 }
4361
4362 // If at least one of the types is a class type, the types are not
4363 // related, and we aren't allowed any user conversions, the
4364 // reference binding fails. This case is important for breaking
4365 // recursion, since TryImplicitConversion below will attempt to
4366 // create a temporary through the use of a copy constructor.
4367 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4368 (T1->isRecordType() || T2->isRecordType()))
4369 return ICS;
4370
Douglas Gregorcba72b12011-01-21 05:18:22 +00004371 // If T1 is reference-related to T2 and the reference is an rvalue
4372 // reference, the initializer expression shall not be an lvalue.
4373 if (RefRelationship >= Sema::Ref_Related &&
4374 isRValRef && Init->Classify(S.Context).isLValue())
4375 return ICS;
4376
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004377 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004378 // When a parameter of reference type is not bound directly to
4379 // an argument expression, the conversion sequence is the one
4380 // required to convert the argument expression to the
4381 // underlying type of the reference according to
4382 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4383 // to copy-initializing a temporary of the underlying type with
4384 // the argument expression. Any difference in top-level
4385 // cv-qualification is subsumed by the initialization itself
4386 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004387 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4388 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004389 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004390 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004391 /*AllowObjCWritebackConversion=*/false,
4392 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004393
4394 // Of course, that's still a reference binding.
4395 if (ICS.isStandard()) {
4396 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004397 ICS.Standard.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004398 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004399 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004400 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004401 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004402 } else if (ICS.isUserDefined()) {
Richard Smith19172c42014-07-14 02:28:44 +00004403 const ReferenceType *LValRefType =
4404 ICS.UserDefined.ConversionFunction->getReturnType()
4405 ->getAs<LValueReferenceType>();
4406
4407 // C++ [over.ics.ref]p3:
4408 // Except for an implicit object parameter, for which see 13.3.1, a
4409 // standard conversion sequence cannot be formed if it requires [...]
4410 // binding an rvalue reference to an lvalue other than a function
4411 // lvalue.
4412 // Note that the function case is not possible here.
4413 if (DeclType->isRValueReferenceType() && LValRefType) {
4414 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4415 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4416 // reference to an rvalue!
4417 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4418 return ICS;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004419 }
Richard Smith19172c42014-07-14 02:28:44 +00004420
Ismail Pazarbasi99afd962014-01-24 10:54:12 +00004421 ICS.UserDefined.Before.setAsIdentityConversion();
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004422 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004423 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004424 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4425 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004426 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4427 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004428 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004429
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004430 return ICS;
4431}
4432
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004433static ImplicitConversionSequence
4434TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4435 bool SuppressUserConversions,
4436 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004437 bool AllowObjCWritebackConversion,
4438 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004439
4440/// TryListConversion - Try to copy-initialize a value of type ToType from the
4441/// initializer list From.
4442static ImplicitConversionSequence
4443TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4444 bool SuppressUserConversions,
4445 bool InOverloadResolution,
4446 bool AllowObjCWritebackConversion) {
4447 // C++11 [over.ics.list]p1:
4448 // When an argument is an initializer list, it is not an expression and
4449 // special rules apply for converting it to a parameter type.
4450
4451 ImplicitConversionSequence Result;
4452 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4453
Sebastian Redl09edce02012-01-23 22:09:39 +00004454 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004455 // initialized from init lists.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004456 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004457 return Result;
4458
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004459 // C++11 [over.ics.list]p2:
4460 // If the parameter type is std::initializer_list<X> or "array of X" and
4461 // all the elements can be implicitly converted to X, the implicit
4462 // conversion sequence is the worst conversion necessary to convert an
4463 // element of the list to X.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004464 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004465 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004466 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004467 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004468 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004469 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004470 if (!X.isNull()) {
4471 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4472 Expr *Init = From->getInit(i);
4473 ImplicitConversionSequence ICS =
4474 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4475 InOverloadResolution,
4476 AllowObjCWritebackConversion);
4477 // If a single element isn't convertible, fail.
4478 if (ICS.isBad()) {
4479 Result = ICS;
4480 break;
4481 }
4482 // Otherwise, look for the worst conversion.
4483 if (Result.isBad() ||
4484 CompareImplicitConversionSequences(S, ICS, Result) ==
4485 ImplicitConversionSequence::Worse)
4486 Result = ICS;
4487 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004488
4489 // For an empty list, we won't have computed any conversion sequence.
4490 // Introduce the identity conversion sequence.
4491 if (From->getNumInits() == 0) {
4492 Result.setStandard();
4493 Result.Standard.setAsIdentityConversion();
4494 Result.Standard.setFromType(ToType);
4495 Result.Standard.setAllToTypes(ToType);
4496 }
4497
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004498 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004499 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004500 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004501
4502 // C++11 [over.ics.list]p3:
4503 // Otherwise, if the parameter is a non-aggregate class X and overload
4504 // resolution chooses a single best constructor [...] the implicit
4505 // conversion sequence is a user-defined conversion sequence. If multiple
4506 // constructors are viable but none is better than the others, the
4507 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004508 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4509 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004510 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4511 /*AllowExplicit=*/false,
4512 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004513 AllowObjCWritebackConversion,
4514 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004515 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004516
4517 // C++11 [over.ics.list]p4:
4518 // Otherwise, if the parameter has an aggregate type which can be
4519 // initialized from the initializer list [...] the implicit conversion
4520 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004521 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004522 // Type is an aggregate, argument is an init list. At this point it comes
4523 // down to checking whether the initialization works.
4524 // FIXME: Find out whether this parameter is consumed or not.
4525 InitializedEntity Entity =
4526 InitializedEntity::InitializeParameter(S.Context, ToType,
4527 /*Consumed=*/false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004528 if (S.CanPerformCopyInitialization(Entity, From)) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004529 Result.setUserDefined();
4530 Result.UserDefined.Before.setAsIdentityConversion();
4531 // Initializer lists don't have a type.
4532 Result.UserDefined.Before.setFromType(QualType());
4533 Result.UserDefined.Before.setAllToTypes(QualType());
4534
4535 Result.UserDefined.After.setAsIdentityConversion();
4536 Result.UserDefined.After.setFromType(ToType);
4537 Result.UserDefined.After.setAllToTypes(ToType);
Craig Topperc3ec1492014-05-26 06:22:03 +00004538 Result.UserDefined.ConversionFunction = nullptr;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004539 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004540 return Result;
4541 }
4542
4543 // C++11 [over.ics.list]p5:
4544 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004545 if (ToType->isReferenceType()) {
4546 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4547 // mention initializer lists in any way. So we go by what list-
4548 // initialization would do and try to extrapolate from that.
4549
4550 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4551
4552 // If the initializer list has a single element that is reference-related
4553 // to the parameter type, we initialize the reference from that.
4554 if (From->getNumInits() == 1) {
4555 Expr *Init = From->getInit(0);
4556
4557 QualType T2 = Init->getType();
4558
4559 // If the initializer is the address of an overloaded function, try
4560 // to resolve the overloaded function. If all goes well, T2 is the
4561 // type of the resulting function.
4562 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4563 DeclAccessPair Found;
4564 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4565 Init, ToType, false, Found))
4566 T2 = Fn->getType();
4567 }
4568
4569 // Compute some basic properties of the types and the initializer.
4570 bool dummy1 = false;
4571 bool dummy2 = false;
4572 bool dummy3 = false;
4573 Sema::ReferenceCompareResult RefRelationship
4574 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4575 dummy2, dummy3);
4576
Richard Smith4d2bbd72013-09-06 01:22:42 +00004577 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004578 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4579 SuppressUserConversions,
4580 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004581 }
Sebastian Redldf888642011-12-03 14:54:30 +00004582 }
4583
4584 // Otherwise, we bind the reference to a temporary created from the
4585 // initializer list.
4586 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4587 InOverloadResolution,
4588 AllowObjCWritebackConversion);
4589 if (Result.isFailure())
4590 return Result;
4591 assert(!Result.isEllipsis() &&
4592 "Sub-initialization cannot result in ellipsis conversion.");
4593
4594 // Can we even bind to a temporary?
4595 if (ToType->isRValueReferenceType() ||
4596 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4597 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4598 Result.UserDefined.After;
4599 SCS.ReferenceBinding = true;
4600 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4601 SCS.BindsToRvalue = true;
4602 SCS.BindsToFunctionLvalue = false;
4603 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4604 SCS.ObjCLifetimeConversionBinding = false;
4605 } else
4606 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4607 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004608 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004609 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004610
4611 // C++11 [over.ics.list]p6:
4612 // Otherwise, if the parameter type is not a class:
4613 if (!ToType->isRecordType()) {
4614 // - if the initializer list has one element, the implicit conversion
4615 // sequence is the one required to convert the element to the
4616 // parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004617 unsigned NumInits = From->getNumInits();
4618 if (NumInits == 1)
4619 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4620 SuppressUserConversions,
4621 InOverloadResolution,
4622 AllowObjCWritebackConversion);
4623 // - if the initializer list has no elements, the implicit conversion
4624 // sequence is the identity conversion.
4625 else if (NumInits == 0) {
4626 Result.setStandard();
4627 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004628 Result.Standard.setFromType(ToType);
4629 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004630 }
4631 return Result;
4632 }
4633
4634 // C++11 [over.ics.list]p7:
4635 // In all cases other than those enumerated above, no conversion is possible
4636 return Result;
4637}
4638
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004639/// TryCopyInitialization - Try to copy-initialize a value of type
4640/// ToType from the expression From. Return the implicit conversion
4641/// sequence required to pass this argument, which may be a bad
4642/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004643/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004644/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004645static ImplicitConversionSequence
4646TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004647 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004648 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004649 bool AllowObjCWritebackConversion,
4650 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004651 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4652 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4653 InOverloadResolution,AllowObjCWritebackConversion);
4654
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004655 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004656 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004657 /*FIXME:*/From->getLocStart(),
4658 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004659 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004660
John McCall5c32be02010-08-24 20:38:10 +00004661 return TryImplicitConversion(S, From, ToType,
4662 SuppressUserConversions,
4663 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004664 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004665 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004666 AllowObjCWritebackConversion,
4667 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004668}
4669
Anna Zaks1b068122011-07-28 19:46:48 +00004670static bool TryCopyInitialization(const CanQualType FromQTy,
4671 const CanQualType ToQTy,
4672 Sema &S,
4673 SourceLocation Loc,
4674 ExprValueKind FromVK) {
4675 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4676 ImplicitConversionSequence ICS =
4677 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4678
4679 return !ICS.isBad();
4680}
4681
Douglas Gregor436424c2008-11-18 23:14:02 +00004682/// TryObjectArgumentInitialization - Try to initialize the object
4683/// parameter of the given member function (@c Method) from the
4684/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004685static ImplicitConversionSequence
Richard Smith03c66d32013-01-26 02:07:32 +00004686TryObjectArgumentInitialization(Sema &S, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004687 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004688 CXXMethodDecl *Method,
4689 CXXRecordDecl *ActingContext) {
4690 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004691 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4692 // const volatile object.
4693 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4694 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004695 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004696
4697 // Set up the conversion sequence as a "bad" conversion, to allow us
4698 // to exit early.
4699 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004700
4701 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00004702 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004703 FromType = PT->getPointeeType();
4704
Douglas Gregor02824322011-01-26 19:30:28 +00004705 // When we had a pointer, it's implicitly dereferenced, so we
4706 // better have an lvalue.
4707 assert(FromClassification.isLValue());
4708 }
4709
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004710 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004711
Douglas Gregor02824322011-01-26 19:30:28 +00004712 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004713 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004714 // parameter is
4715 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004716 // - "lvalue reference to cv X" for functions declared without a
4717 // ref-qualifier or with the & ref-qualifier
4718 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004719 // ref-qualifier
4720 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004721 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004722 // cv-qualification on the member function declaration.
4723 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004724 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004725 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004726 // (C++ [over.match.funcs]p5). We perform a simplified version of
4727 // reference binding here, that allows class rvalues to bind to
4728 // non-constant references.
4729
Douglas Gregor02824322011-01-26 19:30:28 +00004730 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004731 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004732 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004733 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004734 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004735 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00004736 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004737 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004738 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004739
4740 // Check that we have either the same type or a derived type. It
4741 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004742 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004743 ImplicitConversionKind SecondKind;
4744 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4745 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004746 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004747 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004748 else {
John McCall65eb8792010-02-25 01:37:24 +00004749 ICS.setBad(BadConversionSequence::unrelated_class,
4750 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004751 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004752 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004753
Douglas Gregor02824322011-01-26 19:30:28 +00004754 // Check the ref-qualifier.
4755 switch (Method->getRefQualifier()) {
4756 case RQ_None:
4757 // Do nothing; we don't care about lvalueness or rvalueness.
4758 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004759
Douglas Gregor02824322011-01-26 19:30:28 +00004760 case RQ_LValue:
4761 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4762 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004763 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004764 ImplicitParamType);
4765 return ICS;
4766 }
4767 break;
4768
4769 case RQ_RValue:
4770 if (!FromClassification.isRValue()) {
4771 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004772 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004773 ImplicitParamType);
4774 return ICS;
4775 }
4776 break;
4777 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004778
Douglas Gregor436424c2008-11-18 23:14:02 +00004779 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004780 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004781 ICS.Standard.setAsIdentityConversion();
4782 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004783 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004784 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004785 ICS.Standard.ReferenceBinding = true;
4786 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004787 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004788 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004789 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4790 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4791 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004792 return ICS;
4793}
4794
4795/// PerformObjectArgumentInitialization - Perform initialization of
4796/// the implicit object parameter for the given Method with the given
4797/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004798ExprResult
4799Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004800 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004801 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004802 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004803 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004804 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004805 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004806
Douglas Gregor02824322011-01-26 19:30:28 +00004807 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004808 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004809 FromRecordType = PT->getPointeeType();
4810 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004811 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004812 } else {
4813 FromRecordType = From->getType();
4814 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004815 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004816 }
4817
John McCall6e9f8f62009-12-03 04:06:58 +00004818 // Note that we always use the true parent context when performing
4819 // the actual argument initialization.
Nico Weberb58e51c2014-11-19 05:21:39 +00004820 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
4821 *this, From->getType(), FromClassification, Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004822 if (ICS.isBad()) {
4823 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4824 Qualifiers FromQs = FromRecordType.getQualifiers();
4825 Qualifiers ToQs = DestType.getQualifiers();
4826 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4827 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004828 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004829 diag::err_member_function_call_bad_cvr)
4830 << Method->getDeclName() << FromRecordType << (CVR - 1)
4831 << From->getSourceRange();
4832 Diag(Method->getLocation(), diag::note_previous_decl)
4833 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004834 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004835 }
4836 }
4837
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004838 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004839 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004840 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004841 }
Mike Stump11289f42009-09-09 15:08:12 +00004842
John Wiegley01296292011-04-08 18:41:53 +00004843 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4844 ExprResult FromRes =
4845 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4846 if (FromRes.isInvalid())
4847 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004848 From = FromRes.get();
John Wiegley01296292011-04-08 18:41:53 +00004849 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004850
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004851 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004852 From = ImpCastExprToType(From, DestType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004853 From->getValueKind()).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004854 return From;
Douglas Gregor436424c2008-11-18 23:14:02 +00004855}
4856
Douglas Gregor5fb53972009-01-14 15:45:31 +00004857/// TryContextuallyConvertToBool - Attempt to contextually convert the
4858/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004859static ImplicitConversionSequence
4860TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00004861 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004862 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004863 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004864 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004865 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004866 /*AllowObjCWritebackConversion=*/false,
4867 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004868}
4869
4870/// PerformContextuallyConvertToBool - Perform a contextual conversion
4871/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004872ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004873 if (checkPlaceholderForOverload(*this, From))
4874 return ExprError();
4875
John McCall5c32be02010-08-24 20:38:10 +00004876 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004877 if (!ICS.isBad())
4878 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004879
Fariborz Jahanian76197412009-11-18 18:26:29 +00004880 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004881 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00004882 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004883 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004884 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004885}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004886
Richard Smithf8379a02012-01-18 23:55:52 +00004887/// Check that the specified conversion is permitted in a converted constant
4888/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4889/// is acceptable.
4890static bool CheckConvertedConstantConversions(Sema &S,
4891 StandardConversionSequence &SCS) {
4892 // Since we know that the target type is an integral or unscoped enumeration
4893 // type, most conversion kinds are impossible. All possible First and Third
4894 // conversions are fine.
4895 switch (SCS.Second) {
4896 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00004897 case ICK_NoReturn_Adjustment:
Richard Smithf8379a02012-01-18 23:55:52 +00004898 case ICK_Integral_Promotion:
Richard Smith410cc892014-11-26 03:26:53 +00004899 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
Richard Smithf8379a02012-01-18 23:55:52 +00004900 return true;
4901
4902 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00004903 // Conversion from an integral or unscoped enumeration type to bool is
Richard Smith410cc892014-11-26 03:26:53 +00004904 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
4905 // conversion, so we allow it in a converted constant expression.
4906 //
4907 // FIXME: Per core issue 1407, we should not allow this, but that breaks
4908 // a lot of popular code. We should at least add a warning for this
4909 // (non-conforming) extension.
Richard Smithca24ed42012-09-13 22:00:12 +00004910 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4911 SCS.getToType(2)->isBooleanType();
4912
Richard Smith410cc892014-11-26 03:26:53 +00004913 case ICK_Pointer_Conversion:
4914 case ICK_Pointer_Member:
4915 // C++1z: null pointer conversions and null member pointer conversions are
4916 // only permitted if the source type is std::nullptr_t.
4917 return SCS.getFromType()->isNullPtrType();
4918
4919 case ICK_Floating_Promotion:
4920 case ICK_Complex_Promotion:
4921 case ICK_Floating_Conversion:
4922 case ICK_Complex_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00004923 case ICK_Floating_Integral:
Richard Smith410cc892014-11-26 03:26:53 +00004924 case ICK_Compatible_Conversion:
4925 case ICK_Derived_To_Base:
4926 case ICK_Vector_Conversion:
4927 case ICK_Vector_Splat:
Richard Smithf8379a02012-01-18 23:55:52 +00004928 case ICK_Complex_Real:
Richard Smith410cc892014-11-26 03:26:53 +00004929 case ICK_Block_Pointer_Conversion:
4930 case ICK_TransparentUnionConversion:
4931 case ICK_Writeback_Conversion:
4932 case ICK_Zero_Event_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00004933 return false;
4934
4935 case ICK_Lvalue_To_Rvalue:
4936 case ICK_Array_To_Pointer:
4937 case ICK_Function_To_Pointer:
Richard Smith410cc892014-11-26 03:26:53 +00004938 llvm_unreachable("found a first conversion kind in Second");
4939
Richard Smithf8379a02012-01-18 23:55:52 +00004940 case ICK_Qualification:
Richard Smith410cc892014-11-26 03:26:53 +00004941 llvm_unreachable("found a third conversion kind in Second");
Richard Smithf8379a02012-01-18 23:55:52 +00004942
4943 case ICK_Num_Conversion_Kinds:
4944 break;
4945 }
4946
4947 llvm_unreachable("unknown conversion kind");
4948}
4949
4950/// CheckConvertedConstantExpression - Check that the expression From is a
4951/// converted constant expression of type T, perform the conversion and produce
4952/// the converted expression, per C++11 [expr.const]p3.
Richard Smith410cc892014-11-26 03:26:53 +00004953static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
4954 QualType T, APValue &Value,
4955 Sema::CCEKind CCE,
4956 bool RequireInt) {
4957 assert(S.getLangOpts().CPlusPlus11 &&
4958 "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00004959
Richard Smith410cc892014-11-26 03:26:53 +00004960 if (checkPlaceholderForOverload(S, From))
Richard Smithf8379a02012-01-18 23:55:52 +00004961 return ExprError();
4962
Richard Smith410cc892014-11-26 03:26:53 +00004963 // C++1z [expr.const]p3:
4964 // A converted constant expression of type T is an expression,
4965 // implicitly converted to type T, where the converted
4966 // expression is a constant expression and the implicit conversion
4967 // sequence contains only [... list of conversions ...].
Richard Smithf8379a02012-01-18 23:55:52 +00004968 ImplicitConversionSequence ICS =
Richard Smith410cc892014-11-26 03:26:53 +00004969 TryCopyInitialization(S, From, T,
Richard Smithf8379a02012-01-18 23:55:52 +00004970 /*SuppressUserConversions=*/false,
Richard Smithf8379a02012-01-18 23:55:52 +00004971 /*InOverloadResolution=*/false,
Richard Smith410cc892014-11-26 03:26:53 +00004972 /*AllowObjcWritebackConversion=*/false,
4973 /*AllowExplicit=*/false);
Craig Topperc3ec1492014-05-26 06:22:03 +00004974 StandardConversionSequence *SCS = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +00004975 switch (ICS.getKind()) {
4976 case ImplicitConversionSequence::StandardConversion:
Richard Smithf8379a02012-01-18 23:55:52 +00004977 SCS = &ICS.Standard;
4978 break;
4979 case ImplicitConversionSequence::UserDefinedConversion:
Richard Smith410cc892014-11-26 03:26:53 +00004980 // We are converting to a non-class type, so the Before sequence
4981 // must be trivial.
Richard Smithf8379a02012-01-18 23:55:52 +00004982 SCS = &ICS.UserDefined.After;
4983 break;
4984 case ImplicitConversionSequence::AmbiguousConversion:
4985 case ImplicitConversionSequence::BadConversion:
Richard Smith410cc892014-11-26 03:26:53 +00004986 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
4987 return S.Diag(From->getLocStart(),
4988 diag::err_typecheck_converted_constant_expression)
4989 << From->getType() << From->getSourceRange() << T;
Richard Smithf8379a02012-01-18 23:55:52 +00004990 return ExprError();
4991
4992 case ImplicitConversionSequence::EllipsisConversion:
4993 llvm_unreachable("ellipsis conversion in converted constant expression");
4994 }
4995
Richard Smith410cc892014-11-26 03:26:53 +00004996 // Check that we would only use permitted conversions.
4997 if (!CheckConvertedConstantConversions(S, *SCS)) {
4998 return S.Diag(From->getLocStart(),
4999 diag::err_typecheck_converted_constant_expression_disallowed)
5000 << From->getType() << From->getSourceRange() << T;
5001 }
5002 // [...] and where the reference binding (if any) binds directly.
5003 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5004 return S.Diag(From->getLocStart(),
5005 diag::err_typecheck_converted_constant_expression_indirect)
5006 << From->getType() << From->getSourceRange() << T;
5007 }
5008
5009 ExprResult Result =
5010 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
Richard Smithf8379a02012-01-18 23:55:52 +00005011 if (Result.isInvalid())
5012 return Result;
5013
5014 // Check for a narrowing implicit conversion.
5015 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005016 QualType PreNarrowingType;
Richard Smith410cc892014-11-26 03:26:53 +00005017 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
Richard Smith5614ca72012-03-23 23:55:39 +00005018 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00005019 case NK_Variable_Narrowing:
5020 // Implicit conversion to a narrower type, and the value is not a constant
5021 // expression. We'll diagnose this in a moment.
5022 case NK_Not_Narrowing:
5023 break;
5024
5025 case NK_Constant_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005026 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005027 << CCE << /*Constant*/1
Richard Smith410cc892014-11-26 03:26:53 +00005028 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005029 break;
5030
5031 case NK_Type_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005032 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005033 << CCE << /*Constant*/0 << From->getType() << T;
5034 break;
5035 }
5036
5037 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005038 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005039 Expr::EvalResult Eval;
5040 Eval.Diag = &Notes;
5041
Richard Smith410cc892014-11-26 03:26:53 +00005042 if ((T->isReferenceType()
5043 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5044 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5045 (RequireInt && !Eval.Val.isInt())) {
Richard Smithf8379a02012-01-18 23:55:52 +00005046 // The expression can't be folded, so we can't keep it at this position in
5047 // the AST.
5048 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005049 } else {
Richard Smith410cc892014-11-26 03:26:53 +00005050 Value = Eval.Val;
Richard Smith911e1422012-01-30 22:27:01 +00005051
5052 if (Notes.empty()) {
5053 // It's a constant expression.
5054 return Result;
5055 }
Richard Smithf8379a02012-01-18 23:55:52 +00005056 }
5057
5058 // It's not a constant expression. Produce an appropriate diagnostic.
5059 if (Notes.size() == 1 &&
5060 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
Richard Smith410cc892014-11-26 03:26:53 +00005061 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
Richard Smithf8379a02012-01-18 23:55:52 +00005062 else {
Richard Smith410cc892014-11-26 03:26:53 +00005063 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005064 << CCE << From->getSourceRange();
5065 for (unsigned I = 0; I < Notes.size(); ++I)
Richard Smith410cc892014-11-26 03:26:53 +00005066 S.Diag(Notes[I].first, Notes[I].second);
Richard Smithf8379a02012-01-18 23:55:52 +00005067 }
Richard Smith410cc892014-11-26 03:26:53 +00005068 return ExprError();
Richard Smithf8379a02012-01-18 23:55:52 +00005069}
5070
Richard Smith410cc892014-11-26 03:26:53 +00005071ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5072 APValue &Value, CCEKind CCE) {
5073 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5074}
5075
5076ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5077 llvm::APSInt &Value,
5078 CCEKind CCE) {
5079 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5080
5081 APValue V;
5082 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5083 if (!R.isInvalid())
5084 Value = V.getInt();
5085 return R;
5086}
5087
5088
John McCallfec112d2011-09-09 06:11:02 +00005089/// dropPointerConversions - If the given standard conversion sequence
5090/// involves any pointer conversions, remove them. This may change
5091/// the result type of the conversion sequence.
5092static void dropPointerConversion(StandardConversionSequence &SCS) {
5093 if (SCS.Second == ICK_Pointer_Conversion) {
5094 SCS.Second = ICK_Identity;
5095 SCS.Third = ICK_Identity;
5096 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5097 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005098}
John McCall5c32be02010-08-24 20:38:10 +00005099
John McCallfec112d2011-09-09 06:11:02 +00005100/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5101/// convert the expression From to an Objective-C pointer type.
5102static ImplicitConversionSequence
5103TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5104 // Do an implicit conversion to 'id'.
5105 QualType Ty = S.Context.getObjCIdType();
5106 ImplicitConversionSequence ICS
5107 = TryImplicitConversion(S, From, Ty,
5108 // FIXME: Are these flags correct?
5109 /*SuppressUserConversions=*/false,
5110 /*AllowExplicit=*/true,
5111 /*InOverloadResolution=*/false,
5112 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005113 /*AllowObjCWritebackConversion=*/false,
5114 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005115
5116 // Strip off any final conversions to 'id'.
5117 switch (ICS.getKind()) {
5118 case ImplicitConversionSequence::BadConversion:
5119 case ImplicitConversionSequence::AmbiguousConversion:
5120 case ImplicitConversionSequence::EllipsisConversion:
5121 break;
5122
5123 case ImplicitConversionSequence::UserDefinedConversion:
5124 dropPointerConversion(ICS.UserDefined.After);
5125 break;
5126
5127 case ImplicitConversionSequence::StandardConversion:
5128 dropPointerConversion(ICS.Standard);
5129 break;
5130 }
5131
5132 return ICS;
5133}
5134
5135/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5136/// conversion of the expression From to an Objective-C pointer type.
5137ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005138 if (checkPlaceholderForOverload(*this, From))
5139 return ExprError();
5140
John McCall8b07ec22010-05-15 11:32:37 +00005141 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005142 ImplicitConversionSequence ICS =
5143 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005144 if (!ICS.isBad())
5145 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005146 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005147}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005148
Richard Smith8dd34252012-02-04 07:07:42 +00005149/// Determine whether the provided type is an integral type, or an enumeration
5150/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005151bool Sema::ICEConvertDiagnoser::match(QualType T) {
5152 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5153 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005154}
5155
Larisse Voufo236bec22013-06-10 06:50:24 +00005156static ExprResult
5157diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5158 Sema::ContextualImplicitConverter &Converter,
5159 QualType T, UnresolvedSetImpl &ViableConversions) {
5160
5161 if (Converter.Suppress)
5162 return ExprError();
5163
5164 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5165 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5166 CXXConversionDecl *Conv =
5167 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5168 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5169 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5170 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005171 return From;
Larisse Voufo236bec22013-06-10 06:50:24 +00005172}
5173
5174static bool
5175diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5176 Sema::ContextualImplicitConverter &Converter,
5177 QualType T, bool HadMultipleCandidates,
5178 UnresolvedSetImpl &ExplicitConversions) {
5179 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5180 DeclAccessPair Found = ExplicitConversions[0];
5181 CXXConversionDecl *Conversion =
5182 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5183
5184 // The user probably meant to invoke the given explicit
5185 // conversion; use it.
5186 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5187 std::string TypeStr;
5188 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5189
5190 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5191 << FixItHint::CreateInsertion(From->getLocStart(),
5192 "static_cast<" + TypeStr + ">(")
5193 << FixItHint::CreateInsertion(
Alp Tokerb6cc5922014-05-03 03:45:55 +00005194 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
Larisse Voufo236bec22013-06-10 06:50:24 +00005195 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5196
5197 // If we aren't in a SFINAE context, build a call to the
5198 // explicit conversion function.
5199 if (SemaRef.isSFINAEContext())
5200 return true;
5201
Craig Topperc3ec1492014-05-26 06:22:03 +00005202 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005203 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5204 HadMultipleCandidates);
5205 if (Result.isInvalid())
5206 return true;
5207 // Record usage of conversion in an implicit cast.
5208 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005209 CK_UserDefinedConversion, Result.get(),
5210 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005211 }
5212 return false;
5213}
5214
5215static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5216 Sema::ContextualImplicitConverter &Converter,
5217 QualType T, bool HadMultipleCandidates,
5218 DeclAccessPair &Found) {
5219 CXXConversionDecl *Conversion =
5220 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005221 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005222
5223 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5224 if (!Converter.SuppressConversion) {
5225 if (SemaRef.isSFINAEContext())
5226 return true;
5227
5228 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5229 << From->getSourceRange();
5230 }
5231
5232 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5233 HadMultipleCandidates);
5234 if (Result.isInvalid())
5235 return true;
5236 // Record usage of conversion in an implicit cast.
5237 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005238 CK_UserDefinedConversion, Result.get(),
5239 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005240 return false;
5241}
5242
5243static ExprResult finishContextualImplicitConversion(
5244 Sema &SemaRef, SourceLocation Loc, Expr *From,
5245 Sema::ContextualImplicitConverter &Converter) {
5246 if (!Converter.match(From->getType()) && !Converter.Suppress)
5247 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5248 << From->getSourceRange();
5249
5250 return SemaRef.DefaultLvalueConversion(From);
5251}
5252
5253static void
5254collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5255 UnresolvedSetImpl &ViableConversions,
5256 OverloadCandidateSet &CandidateSet) {
5257 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5258 DeclAccessPair FoundDecl = ViableConversions[I];
5259 NamedDecl *D = FoundDecl.getDecl();
5260 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5261 if (isa<UsingShadowDecl>(D))
5262 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5263
5264 CXXConversionDecl *Conv;
5265 FunctionTemplateDecl *ConvTemplate;
5266 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5267 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5268 else
5269 Conv = cast<CXXConversionDecl>(D);
5270
5271 if (ConvTemplate)
5272 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005273 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5274 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005275 else
5276 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005277 ToType, CandidateSet,
5278 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005279 }
5280}
5281
Richard Smithccc11812013-05-21 19:05:48 +00005282/// \brief Attempt to convert the given expression to a type which is accepted
5283/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005284///
Richard Smithccc11812013-05-21 19:05:48 +00005285/// This routine will attempt to convert an expression of class type to a
5286/// type accepted by the specified converter. In C++11 and before, the class
5287/// must have a single non-explicit conversion function converting to a matching
5288/// type. In C++1y, there can be multiple such conversion functions, but only
5289/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005290///
Douglas Gregor4799d032010-06-30 00:20:43 +00005291/// \param Loc The source location of the construct that requires the
5292/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005293///
James Dennett18348b62012-06-22 08:52:37 +00005294/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005295///
Richard Smithccc11812013-05-21 19:05:48 +00005296/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005297///
Douglas Gregor4799d032010-06-30 00:20:43 +00005298/// \returns The expression, converted to an integral or enumeration type if
5299/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005300ExprResult Sema::PerformContextualImplicitConversion(
5301 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005302 // We can't perform any more checking for type-dependent expressions.
5303 if (From->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005304 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005305
Eli Friedman1da70392012-01-26 00:26:18 +00005306 // Process placeholders immediately.
5307 if (From->hasPlaceholderType()) {
5308 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005309 if (result.isInvalid())
5310 return result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005311 From = result.get();
Eli Friedman1da70392012-01-26 00:26:18 +00005312 }
5313
Richard Smithccc11812013-05-21 19:05:48 +00005314 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005315 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005316 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005317 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005318
5319 // FIXME: Check for missing '()' if T is a function type?
5320
Richard Smithccc11812013-05-21 19:05:48 +00005321 // We can only perform contextual implicit conversions on objects of class
5322 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005323 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005324 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005325 if (!Converter.Suppress)
5326 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005327 return From;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005328 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005329
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005330 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005331 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005332 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005333 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005334
5335 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5336 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5337
Craig Toppere14c0f82014-03-12 04:55:44 +00005338 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00005339 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005340 }
Richard Smithccc11812013-05-21 19:05:48 +00005341 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005342
5343 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005344 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005345
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005346 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005347 UnresolvedSet<4>
5348 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005349 UnresolvedSet<4> ExplicitConversions;
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00005350 std::pair<CXXRecordDecl::conversion_iterator,
Larisse Voufo236bec22013-06-10 06:50:24 +00005351 CXXRecordDecl::conversion_iterator> Conversions =
5352 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005353
Larisse Voufo236bec22013-06-10 06:50:24 +00005354 bool HadMultipleCandidates =
5355 (std::distance(Conversions.first, Conversions.second) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005356
Larisse Voufo236bec22013-06-10 06:50:24 +00005357 // To check that there is only one target type, in C++1y:
5358 QualType ToType;
5359 bool HasUniqueTargetType = true;
5360
5361 // Collect explicit or viable (potentially in C++1y) conversions.
5362 for (CXXRecordDecl::conversion_iterator I = Conversions.first,
5363 E = Conversions.second;
5364 I != E; ++I) {
5365 NamedDecl *D = (*I)->getUnderlyingDecl();
5366 CXXConversionDecl *Conversion;
5367 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5368 if (ConvTemplate) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005369 if (getLangOpts().CPlusPlus14)
Larisse Voufo236bec22013-06-10 06:50:24 +00005370 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5371 else
5372 continue; // C++11 does not consider conversion operator templates(?).
5373 } else
5374 Conversion = cast<CXXConversionDecl>(D);
5375
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005376 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
Larisse Voufo236bec22013-06-10 06:50:24 +00005377 "Conversion operator templates are considered potentially "
5378 "viable in C++1y");
5379
5380 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5381 if (Converter.match(CurToType) || ConvTemplate) {
5382
5383 if (Conversion->isExplicit()) {
5384 // FIXME: For C++1y, do we need this restriction?
5385 // cf. diagnoseNoViableConversion()
5386 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005387 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005388 } else {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005389 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005390 if (ToType.isNull())
5391 ToType = CurToType.getUnqualifiedType();
5392 else if (HasUniqueTargetType &&
5393 (CurToType.getUnqualifiedType() != ToType))
5394 HasUniqueTargetType = false;
5395 }
5396 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005397 }
Richard Smith8dd34252012-02-04 07:07:42 +00005398 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005399 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005400
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005401 if (getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005402 // C++1y [conv]p6:
5403 // ... An expression e of class type E appearing in such a context
5404 // is said to be contextually implicitly converted to a specified
5405 // type T and is well-formed if and only if e can be implicitly
5406 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005407 // for conversion functions whose return type is cv T or reference to
5408 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005409 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005410
Larisse Voufo236bec22013-06-10 06:50:24 +00005411 // If no unique T is found:
5412 if (ToType.isNull()) {
5413 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5414 HadMultipleCandidates,
5415 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005416 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005417 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005418 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005419
Larisse Voufo236bec22013-06-10 06:50:24 +00005420 // If more than one unique Ts are found:
5421 if (!HasUniqueTargetType)
5422 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5423 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005424
Larisse Voufo236bec22013-06-10 06:50:24 +00005425 // If one unique T is found:
5426 // First, build a candidate set from the previously recorded
5427 // potentially viable conversions.
Richard Smith100b24a2014-04-17 01:52:14 +00005428 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo236bec22013-06-10 06:50:24 +00005429 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5430 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005431
Larisse Voufo236bec22013-06-10 06:50:24 +00005432 // Then, perform overload resolution over the candidate set.
5433 OverloadCandidateSet::iterator Best;
5434 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5435 case OR_Success: {
5436 // Apply this conversion.
5437 DeclAccessPair Found =
5438 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5439 if (recordConversion(*this, Loc, From, Converter, T,
5440 HadMultipleCandidates, Found))
5441 return ExprError();
5442 break;
5443 }
5444 case OR_Ambiguous:
5445 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5446 ViableConversions);
5447 case OR_No_Viable_Function:
5448 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5449 HadMultipleCandidates,
5450 ExplicitConversions))
5451 return ExprError();
5452 // fall through 'OR_Deleted' case.
5453 case OR_Deleted:
5454 // We'll complain below about a non-integral condition type.
5455 break;
5456 }
5457 } else {
5458 switch (ViableConversions.size()) {
5459 case 0: {
5460 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5461 HadMultipleCandidates,
5462 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005463 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005464
Larisse Voufo236bec22013-06-10 06:50:24 +00005465 // We'll complain below about a non-integral condition type.
5466 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005467 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005468 case 1: {
5469 // Apply this conversion.
5470 DeclAccessPair Found = ViableConversions[0];
5471 if (recordConversion(*this, Loc, From, Converter, T,
5472 HadMultipleCandidates, Found))
5473 return ExprError();
5474 break;
5475 }
5476 default:
5477 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5478 ViableConversions);
5479 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005480 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005481
Larisse Voufo236bec22013-06-10 06:50:24 +00005482 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005483}
5484
Richard Smith100b24a2014-04-17 01:52:14 +00005485/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5486/// an acceptable non-member overloaded operator for a call whose
5487/// arguments have types T1 (and, if non-empty, T2). This routine
5488/// implements the check in C++ [over.match.oper]p3b2 concerning
5489/// enumeration types.
5490static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5491 FunctionDecl *Fn,
5492 ArrayRef<Expr *> Args) {
5493 QualType T1 = Args[0]->getType();
5494 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5495
5496 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5497 return true;
5498
5499 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5500 return true;
5501
5502 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5503 if (Proto->getNumParams() < 1)
5504 return false;
5505
5506 if (T1->isEnumeralType()) {
5507 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5508 if (Context.hasSameUnqualifiedType(T1, ArgType))
5509 return true;
5510 }
5511
5512 if (Proto->getNumParams() < 2)
5513 return false;
5514
5515 if (!T2.isNull() && T2->isEnumeralType()) {
5516 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5517 if (Context.hasSameUnqualifiedType(T2, ArgType))
5518 return true;
5519 }
5520
5521 return false;
5522}
5523
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005524/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005525/// candidate functions, using the given function call arguments. If
5526/// @p SuppressUserConversions, then don't allow user-defined
5527/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005528///
James Dennett2a4d13c2012-06-15 07:13:21 +00005529/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005530/// based on an incomplete set of function arguments. This feature is used by
5531/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005532void
5533Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005534 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005535 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005536 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005537 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005538 bool PartialOverloading,
5539 bool AllowExplicit) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005540 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005541 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005542 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005543 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005544 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005545
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005546 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005547 if (!isa<CXXConstructorDecl>(Method)) {
5548 // If we get here, it's because we're calling a member function
5549 // that is named without a member access expression (e.g.,
5550 // "this->f") that was either written explicitly or created
5551 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005552 // function, e.g., X::f(). We use an empty type for the implied
5553 // object argument (C++ [over.call.func]p3), and the acting context
5554 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005555 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005556 QualType(), Expr::Classification::makeSimpleLValue(),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005557 Args, CandidateSet, SuppressUserConversions,
5558 PartialOverloading);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005559 return;
5560 }
5561 // We treat a constructor like a non-member function, since its object
5562 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005563 }
5564
Douglas Gregorff7028a2009-11-13 23:59:09 +00005565 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005566 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005567
Richard Smith100b24a2014-04-17 01:52:14 +00005568 // C++ [over.match.oper]p3:
5569 // if no operand has a class type, only those non-member functions in the
5570 // lookup set that have a first parameter of type T1 or "reference to
5571 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5572 // is a right operand) a second parameter of type T2 or "reference to
5573 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5574 // candidate functions.
5575 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5576 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5577 return;
5578
Richard Smith8b86f2d2013-11-04 01:48:18 +00005579 // C++11 [class.copy]p11: [DR1402]
5580 // A defaulted move constructor that is defined as deleted is ignored by
5581 // overload resolution.
5582 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5583 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5584 Constructor->isMoveConstructor())
5585 return;
5586
Douglas Gregor27381f32009-11-23 12:27:39 +00005587 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005588 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005589
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005590 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005591 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005592 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005593 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005594 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005595 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005596 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005597 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005598
John McCall578a1f82014-12-14 01:46:53 +00005599 if (Constructor) {
5600 // C++ [class.copy]p3:
5601 // A member function template is never instantiated to perform the copy
5602 // of a class object to an object of its class type.
5603 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5604 if (Args.size() == 1 &&
5605 Constructor->isSpecializationCopyingObject() &&
5606 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5607 IsDerivedFrom(Args[0]->getType(), ClassType))) {
5608 Candidate.Viable = false;
5609 Candidate.FailureKind = ovl_fail_illegal_constructor;
5610 return;
5611 }
5612 }
5613
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005614 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005615
5616 // (C++ 13.3.2p2): A candidate function having fewer than m
5617 // parameters is viable only if it has an ellipsis in its parameter
5618 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005619 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005620 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005621 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005622 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005623 return;
5624 }
5625
5626 // (C++ 13.3.2p2): A candidate function having more than m parameters
5627 // is viable only if the (m+1)st parameter has a default argument
5628 // (8.3.6). For the purposes of overload resolution, the
5629 // parameter list is truncated on the right, so that there are
5630 // exactly m parameters.
5631 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005632 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005633 // Not enough arguments.
5634 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005635 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005636 return;
5637 }
5638
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005639 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005640 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005641 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005642 // Skip the check for callers that are implicit members, because in this
5643 // case we may not yet know what the member's target is; the target is
5644 // inferred for the member automatically, based on the bases and fields of
5645 // the class.
5646 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005647 Candidate.Viable = false;
5648 Candidate.FailureKind = ovl_fail_bad_target;
5649 return;
5650 }
5651
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005652 // Determine the implicit conversion sequences for each of the
5653 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005654 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005655 if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005656 // (C++ 13.3.2p3): for F to be a viable function, there shall
5657 // exist for each argument an implicit conversion sequence
5658 // (13.3.3.1) that converts that argument to the corresponding
5659 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005660 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005661 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005662 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005663 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005664 /*InOverloadResolution=*/true,
5665 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005666 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005667 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005668 if (Candidate.Conversions[ArgIdx].isBad()) {
5669 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005670 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005671 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005672 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005673 } else {
5674 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5675 // argument for which there is no corresponding parameter is
5676 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005677 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005678 }
5679 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005680
5681 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5682 Candidate.Viable = false;
5683 Candidate.FailureKind = ovl_fail_enable_if;
5684 Candidate.DeductionFailure.Data = FailedAttr;
5685 return;
5686 }
5687}
5688
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005689ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args,
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00005690 bool IsInstance) {
5691 SmallVector<ObjCMethodDecl*, 4> Methods;
5692 if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance))
5693 return nullptr;
5694
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005695 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5696 bool Match = true;
5697 ObjCMethodDecl *Method = Methods[b];
5698 unsigned NumNamedArgs = Sel.getNumArgs();
5699 // Method might have more arguments than selector indicates. This is due
5700 // to addition of c-style arguments in method.
5701 if (Method->param_size() > NumNamedArgs)
5702 NumNamedArgs = Method->param_size();
5703 if (Args.size() < NumNamedArgs)
5704 continue;
5705
5706 for (unsigned i = 0; i < NumNamedArgs; i++) {
5707 // We can't do any type-checking on a type-dependent argument.
5708 if (Args[i]->isTypeDependent()) {
5709 Match = false;
5710 break;
5711 }
5712
5713 ParmVarDecl *param = Method->parameters()[i];
5714 Expr *argExpr = Args[i];
5715 assert(argExpr && "SelectBestMethod(): missing expression");
5716
5717 // Strip the unbridged-cast placeholder expression off unless it's
5718 // a consumed argument.
5719 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5720 !param->hasAttr<CFConsumedAttr>())
5721 argExpr = stripARCUnbridgedCast(argExpr);
5722
5723 // If the parameter is __unknown_anytype, move on to the next method.
5724 if (param->getType() == Context.UnknownAnyTy) {
5725 Match = false;
5726 break;
5727 }
5728
5729 ImplicitConversionSequence ConversionState
5730 = TryCopyInitialization(*this, argExpr, param->getType(),
5731 /*SuppressUserConversions*/false,
5732 /*InOverloadResolution=*/true,
5733 /*AllowObjCWritebackConversion=*/
5734 getLangOpts().ObjCAutoRefCount,
5735 /*AllowExplicit*/false);
5736 if (ConversionState.isBad()) {
5737 Match = false;
5738 break;
5739 }
5740 }
5741 // Promote additional arguments to variadic methods.
5742 if (Match && Method->isVariadic()) {
5743 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
5744 if (Args[i]->isTypeDependent()) {
5745 Match = false;
5746 break;
5747 }
5748 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
5749 nullptr);
5750 if (Arg.isInvalid()) {
5751 Match = false;
5752 break;
5753 }
5754 }
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005755 } else {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005756 // Check for extra arguments to non-variadic methods.
5757 if (Args.size() != NumNamedArgs)
5758 Match = false;
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005759 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
5760 // Special case when selectors have no argument. In this case, select
5761 // one with the most general result type of 'id'.
5762 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5763 QualType ReturnT = Methods[b]->getReturnType();
5764 if (ReturnT->isObjCIdType())
5765 return Methods[b];
5766 }
5767 }
5768 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005769
5770 if (Match)
5771 return Method;
5772 }
5773 return nullptr;
5774}
5775
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005776static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); }
5777
5778EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5779 bool MissingImplicitThis) {
5780 // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but
5781 // we need to find the first failing one.
5782 if (!Function->hasAttrs())
Craig Topperc3ec1492014-05-26 06:22:03 +00005783 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005784 AttrVec Attrs = Function->getAttrs();
5785 AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(),
5786 IsNotEnableIfAttr);
5787 if (Attrs.begin() == E)
Craig Topperc3ec1492014-05-26 06:22:03 +00005788 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005789 std::reverse(Attrs.begin(), E);
5790
5791 SFINAETrap Trap(*this);
5792
5793 // Convert the arguments.
5794 SmallVector<Expr *, 16> ConvertedArgs;
5795 bool InitializationFailed = false;
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005796 bool ContainsValueDependentExpr = false;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005797 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5798 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
Nick Lewyckyb8336b72014-02-28 05:26:13 +00005799 !cast<CXXMethodDecl>(Function)->isStatic() &&
5800 !isa<CXXConstructorDecl>(Function)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005801 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5802 ExprResult R =
Craig Topperc3ec1492014-05-26 06:22:03 +00005803 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005804 Method, Method);
5805 if (R.isInvalid()) {
5806 InitializationFailed = true;
5807 break;
5808 }
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005809 ContainsValueDependentExpr |= R.get()->isValueDependent();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005810 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005811 } else {
5812 ExprResult R =
5813 PerformCopyInitialization(InitializedEntity::InitializeParameter(
5814 Context,
5815 Function->getParamDecl(i)),
5816 SourceLocation(),
5817 Args[i]);
5818 if (R.isInvalid()) {
5819 InitializationFailed = true;
5820 break;
5821 }
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005822 ContainsValueDependentExpr |= R.get()->isValueDependent();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005823 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005824 }
5825 }
5826
5827 if (InitializationFailed || Trap.hasErrorOccurred())
5828 return cast<EnableIfAttr>(Attrs[0]);
5829
5830 for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) {
5831 APValue Result;
5832 EnableIfAttr *EIA = cast<EnableIfAttr>(*I);
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005833 if (EIA->getCond()->isValueDependent()) {
5834 // Don't even try now, we'll examine it after instantiation.
5835 continue;
5836 }
5837
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005838 if (!EIA->getCond()->EvaluateWithSubstitution(
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005839 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) {
5840 if (!ContainsValueDependentExpr)
5841 return EIA;
5842 } else if (!Result.isInt() || !Result.getInt().getBoolValue()) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005843 return EIA;
5844 }
5845 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005846 return nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005847}
5848
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005849/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00005850/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00005851void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005852 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005853 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005854 TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smithbcc22fc2012-03-09 08:00:36 +00005855 bool SuppressUserConversions,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005856 bool PartialOverloading) {
John McCall4c4c1df2010-01-26 03:27:55 +00005857 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00005858 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5859 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005860 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005861 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005862 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00005863 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005864 Args.slice(1), CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005865 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005866 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005867 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005868 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005869 } else {
John McCalla0296f72010-03-19 07:35:19 +00005870 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005871 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5872 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005873 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005874 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005875 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005876 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005877 Args[0]->Classify(Context), Args.slice(1),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005878 CandidateSet, SuppressUserConversions,
5879 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005880 else
John McCalla0296f72010-03-19 07:35:19 +00005881 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005882 ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005883 CandidateSet, SuppressUserConversions,
5884 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005885 }
Douglas Gregor15448f82009-06-27 21:05:07 +00005886 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005887}
5888
John McCallf0f1cf02009-11-17 07:50:12 +00005889/// AddMethodCandidate - Adds a named decl (which is some kind of
5890/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00005891void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005892 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005893 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005894 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00005895 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005896 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00005897 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00005898 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00005899
5900 if (isa<UsingShadowDecl>(Decl))
5901 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005902
John McCallf0f1cf02009-11-17 07:50:12 +00005903 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5904 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5905 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00005906 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
Craig Topperc3ec1492014-05-26 06:22:03 +00005907 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005908 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005909 Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005910 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005911 } else {
John McCalla0296f72010-03-19 07:35:19 +00005912 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005913 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005914 Args,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005915 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005916 }
5917}
5918
Douglas Gregor436424c2008-11-18 23:14:02 +00005919/// AddMethodCandidate - Adds the given C++ member function to the set
5920/// of candidate functions, using the given function call arguments
5921/// and the object argument (@c Object). For example, in a call
5922/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5923/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5924/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00005925/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00005926void
John McCalla0296f72010-03-19 07:35:19 +00005927Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00005928 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005929 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005930 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005931 OverloadCandidateSet &CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005932 bool SuppressUserConversions,
5933 bool PartialOverloading) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005934 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005935 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00005936 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005937 assert(!isa<CXXConstructorDecl>(Method) &&
5938 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00005939
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005940 if (!CandidateSet.isNewCandidate(Method))
5941 return;
5942
Richard Smith8b86f2d2013-11-04 01:48:18 +00005943 // C++11 [class.copy]p23: [DR1402]
5944 // A defaulted move assignment operator that is defined as deleted is
5945 // ignored by overload resolution.
5946 if (Method->isDefaulted() && Method->isDeleted() &&
5947 Method->isMoveAssignmentOperator())
5948 return;
5949
Douglas Gregor27381f32009-11-23 12:27:39 +00005950 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005951 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005952
Douglas Gregor436424c2008-11-18 23:14:02 +00005953 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005954 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00005955 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00005956 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005957 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005958 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005959 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00005960
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005961 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00005962
5963 // (C++ 13.3.2p2): A candidate function having fewer than m
5964 // parameters is viable only if it has an ellipsis in its parameter
5965 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005966 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
5967 !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005968 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005969 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005970 return;
5971 }
5972
5973 // (C++ 13.3.2p2): A candidate function having more than m parameters
5974 // is viable only if the (m+1)st parameter has a default argument
5975 // (8.3.6). For the purposes of overload resolution, the
5976 // parameter list is truncated on the right, so that there are
5977 // exactly m parameters.
5978 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005979 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005980 // Not enough arguments.
5981 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005982 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005983 return;
5984 }
5985
5986 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00005987
John McCall6e9f8f62009-12-03 04:06:58 +00005988 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005989 // The implicit object argument is ignored.
5990 Candidate.IgnoreObjectArgument = true;
5991 else {
5992 // Determine the implicit conversion sequence for the object
5993 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00005994 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00005995 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5996 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005997 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005998 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005999 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006000 return;
6001 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006002 }
6003
Eli Bendersky291a57e2014-09-25 23:59:08 +00006004 // (CUDA B.1): Check for invalid calls between targets.
6005 if (getLangOpts().CUDA)
6006 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6007 if (CheckCUDATarget(Caller, Method)) {
6008 Candidate.Viable = false;
6009 Candidate.FailureKind = ovl_fail_bad_target;
6010 return;
6011 }
6012
Douglas Gregor436424c2008-11-18 23:14:02 +00006013 // Determine the implicit conversion sequences for each of the
6014 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006015 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006016 if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006017 // (C++ 13.3.2p3): for F to be a viable function, there shall
6018 // exist for each argument an implicit conversion sequence
6019 // (13.3.3.1) that converts that argument to the corresponding
6020 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006021 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006022 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006023 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006024 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006025 /*InOverloadResolution=*/true,
6026 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006027 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006028 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006029 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006030 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006031 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006032 }
6033 } else {
6034 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6035 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006036 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006037 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00006038 }
6039 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006040
6041 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6042 Candidate.Viable = false;
6043 Candidate.FailureKind = ovl_fail_enable_if;
6044 Candidate.DeductionFailure.Data = FailedAttr;
6045 return;
6046 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006047}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006048
Douglas Gregor97628d62009-08-21 00:16:32 +00006049/// \brief Add a C++ member function template as a candidate to the candidate
6050/// set, using template argument deduction to produce an appropriate member
6051/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006052void
Douglas Gregor97628d62009-08-21 00:16:32 +00006053Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00006054 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006055 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006056 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006057 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006058 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006059 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00006060 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006061 bool SuppressUserConversions,
6062 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006063 if (!CandidateSet.isNewCandidate(MethodTmpl))
6064 return;
6065
Douglas Gregor97628d62009-08-21 00:16:32 +00006066 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006067 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006068 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006069 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00006070 // candidate functions in the usual way.113) A given name can refer to one
6071 // or more function templates and also to a set of overloaded non-template
6072 // functions. In such a case, the candidate functions generated from each
6073 // function template are combined with the set of non-template candidate
6074 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006075 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006076 FunctionDecl *Specialization = nullptr;
Douglas Gregor97628d62009-08-21 00:16:32 +00006077 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006078 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006079 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006080 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006081 Candidate.FoundDecl = FoundDecl;
6082 Candidate.Function = MethodTmpl->getTemplatedDecl();
6083 Candidate.Viable = false;
6084 Candidate.FailureKind = ovl_fail_bad_deduction;
6085 Candidate.IsSurrogate = false;
6086 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006087 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006088 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006089 Info);
6090 return;
6091 }
Mike Stump11289f42009-09-09 15:08:12 +00006092
Douglas Gregor97628d62009-08-21 00:16:32 +00006093 // Add the function template specialization produced by template argument
6094 // deduction as a candidate.
6095 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00006096 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00006097 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00006098 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006099 ActingContext, ObjectType, ObjectClassification, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006100 CandidateSet, SuppressUserConversions, PartialOverloading);
Douglas Gregor97628d62009-08-21 00:16:32 +00006101}
6102
Douglas Gregor05155d82009-08-21 23:19:43 +00006103/// \brief Add a C++ function template specialization as a candidate
6104/// in the candidate set, using template argument deduction to produce
6105/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006106void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006107Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006108 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006109 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006110 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006111 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006112 bool SuppressUserConversions,
6113 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006114 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6115 return;
6116
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006117 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006118 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006119 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006120 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006121 // candidate functions in the usual way.113) A given name can refer to one
6122 // or more function templates and also to a set of overloaded non-template
6123 // functions. In such a case, the candidate functions generated from each
6124 // function template are combined with the set of non-template candidate
6125 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006126 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006127 FunctionDecl *Specialization = nullptr;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006128 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006129 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006130 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006131 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00006132 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00006133 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6134 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006135 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00006136 Candidate.IsSurrogate = false;
6137 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006138 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006139 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006140 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006141 return;
6142 }
Mike Stump11289f42009-09-09 15:08:12 +00006143
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006144 // Add the function template specialization produced by template argument
6145 // deduction as a candidate.
6146 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006147 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006148 SuppressUserConversions, PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006149}
Mike Stump11289f42009-09-09 15:08:12 +00006150
Douglas Gregor4b60a152013-11-07 22:34:54 +00006151/// Determine whether this is an allowable conversion from the result
6152/// of an explicit conversion operator to the expected type, per C++
6153/// [over.match.conv]p1 and [over.match.ref]p1.
6154///
6155/// \param ConvType The return type of the conversion function.
6156///
6157/// \param ToType The type we are converting to.
6158///
6159/// \param AllowObjCPointerConversion Allow a conversion from one
6160/// Objective-C pointer to another.
6161///
6162/// \returns true if the conversion is allowable, false otherwise.
6163static bool isAllowableExplicitConversion(Sema &S,
6164 QualType ConvType, QualType ToType,
6165 bool AllowObjCPointerConversion) {
6166 QualType ToNonRefType = ToType.getNonReferenceType();
6167
6168 // Easy case: the types are the same.
6169 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6170 return true;
6171
6172 // Allow qualification conversions.
6173 bool ObjCLifetimeConversion;
6174 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6175 ObjCLifetimeConversion))
6176 return true;
6177
6178 // If we're not allowed to consider Objective-C pointer conversions,
6179 // we're done.
6180 if (!AllowObjCPointerConversion)
6181 return false;
6182
6183 // Is this an Objective-C pointer conversion?
6184 bool IncompatibleObjC = false;
6185 QualType ConvertedType;
6186 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6187 IncompatibleObjC);
6188}
6189
Douglas Gregora1f013e2008-11-07 22:36:19 +00006190/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006191/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006192/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006193/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006194/// (which may or may not be the same type as the type that the
6195/// conversion function produces).
6196void
6197Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006198 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006199 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006200 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006201 OverloadCandidateSet& CandidateSet,
6202 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006203 assert(!Conversion->getDescribedFunctionTemplate() &&
6204 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006205 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006206 if (!CandidateSet.isNewCandidate(Conversion))
6207 return;
6208
Richard Smith2a7d4812013-05-04 07:00:32 +00006209 // If the conversion function has an undeduced return type, trigger its
6210 // deduction now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006211 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00006212 if (DeduceReturnType(Conversion, From->getExprLoc()))
6213 return;
6214 ConvType = Conversion->getConversionType().getNonReferenceType();
6215 }
6216
Richard Smith089c3162013-09-21 21:55:46 +00006217 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6218 // operator is only a candidate if its return type is the target type or
6219 // can be converted to the target type with a qualification conversion.
Douglas Gregor4b60a152013-11-07 22:34:54 +00006220 if (Conversion->isExplicit() &&
6221 !isAllowableExplicitConversion(*this, ConvType, ToType,
6222 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006223 return;
6224
Douglas Gregor27381f32009-11-23 12:27:39 +00006225 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006226 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006227
Douglas Gregora1f013e2008-11-07 22:36:19 +00006228 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006229 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006230 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006231 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006232 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006233 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006234 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006235 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006236 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006237 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006238 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006239
Douglas Gregor6affc782010-08-19 15:37:02 +00006240 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006241 // For conversion functions, the function is considered to be a member of
6242 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006243 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006244 //
6245 // Determine the implicit conversion sequence for the implicit
6246 // object parameter.
6247 QualType ImplicitParamType = From->getType();
6248 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6249 ImplicitParamType = FromPtrType->getPointeeType();
6250 CXXRecordDecl *ConversionContext
6251 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006252
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006253 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006254 = TryObjectArgumentInitialization(*this, From->getType(),
6255 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00006256 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006257
John McCall0d1da222010-01-12 00:44:57 +00006258 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006259 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006260 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006261 return;
6262 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006263
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006264 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006265 // derived to base as such conversions are given Conversion Rank. They only
6266 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6267 QualType FromCanon
6268 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6269 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6270 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
6271 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006272 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006273 return;
6274 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006275
Douglas Gregora1f013e2008-11-07 22:36:19 +00006276 // To determine what the conversion from the result of calling the
6277 // conversion function to the type we're eventually trying to
6278 // convert to (ToType), we need to synthesize a call to the
6279 // conversion function and attempt copy initialization from it. This
6280 // makes sure that we get the right semantics with respect to
6281 // lvalues/rvalues and the type. Fortunately, we can allocate this
6282 // call on the stack and we don't need its arguments to be
6283 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006284 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006285 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006286 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6287 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006288 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006289 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006290
Richard Smith48d24642011-07-13 22:53:21 +00006291 QualType ConversionType = Conversion->getConversionType();
6292 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006293 Candidate.Viable = false;
6294 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6295 return;
6296 }
6297
Richard Smith48d24642011-07-13 22:53:21 +00006298 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006299
Mike Stump11289f42009-09-09 15:08:12 +00006300 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006301 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6302 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006303 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006304 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006305 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006306 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006307 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006308 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006309 /*InOverloadResolution=*/false,
6310 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006311
John McCall0d1da222010-01-12 00:44:57 +00006312 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006313 case ImplicitConversionSequence::StandardConversion:
6314 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006315
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006316 // C++ [over.ics.user]p3:
6317 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006318 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006319 // shall have exact match rank.
6320 if (Conversion->getPrimaryTemplate() &&
6321 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6322 Candidate.Viable = false;
6323 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006324 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006325 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006326
Douglas Gregorcba72b12011-01-21 05:18:22 +00006327 // C++0x [dcl.init.ref]p5:
6328 // In the second case, if the reference is an rvalue reference and
6329 // the second standard conversion sequence of the user-defined
6330 // conversion sequence includes an lvalue-to-rvalue conversion, the
6331 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006332 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006333 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6334 Candidate.Viable = false;
6335 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006336 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006337 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006338 break;
6339
6340 case ImplicitConversionSequence::BadConversion:
6341 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006342 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006343 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006344
6345 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006346 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006347 "Can only end up with a standard conversion sequence or failure");
6348 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006349
Craig Topper5fc8fc22014-08-27 06:28:36 +00006350 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006351 Candidate.Viable = false;
6352 Candidate.FailureKind = ovl_fail_enable_if;
6353 Candidate.DeductionFailure.Data = FailedAttr;
6354 return;
6355 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006356}
6357
Douglas Gregor05155d82009-08-21 23:19:43 +00006358/// \brief Adds a conversion function template specialization
6359/// candidate to the overload set, using template argument deduction
6360/// to deduce the template arguments of the conversion function
6361/// template from the type that we are converting to (C++
6362/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006363void
Douglas Gregor05155d82009-08-21 23:19:43 +00006364Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006365 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006366 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00006367 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006368 OverloadCandidateSet &CandidateSet,
6369 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006370 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6371 "Only conversion function templates permitted here");
6372
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006373 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6374 return;
6375
Craig Toppere6706e42012-09-19 02:26:47 +00006376 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006377 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00006378 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006379 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006380 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006381 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006382 Candidate.FoundDecl = FoundDecl;
6383 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6384 Candidate.Viable = false;
6385 Candidate.FailureKind = ovl_fail_bad_deduction;
6386 Candidate.IsSurrogate = false;
6387 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006388 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006389 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006390 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006391 return;
6392 }
Mike Stump11289f42009-09-09 15:08:12 +00006393
Douglas Gregor05155d82009-08-21 23:19:43 +00006394 // Add the conversion function template specialization produced by
6395 // template argument deduction as a candidate.
6396 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00006397 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006398 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor05155d82009-08-21 23:19:43 +00006399}
6400
Douglas Gregorab7897a2008-11-19 22:57:39 +00006401/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6402/// converts the given @c Object to a function pointer via the
6403/// conversion function @c Conversion, and then attempts to call it
6404/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6405/// the type of function that we'll eventually be calling.
6406void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006407 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006408 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006409 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00006410 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006411 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00006412 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006413 if (!CandidateSet.isNewCandidate(Conversion))
6414 return;
6415
Douglas Gregor27381f32009-11-23 12:27:39 +00006416 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006417 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006418
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006419 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006420 Candidate.FoundDecl = FoundDecl;
Craig Topperc3ec1492014-05-26 06:22:03 +00006421 Candidate.Function = nullptr;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006422 Candidate.Surrogate = Conversion;
6423 Candidate.Viable = true;
6424 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006425 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006426 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006427
6428 // Determine the implicit conversion sequence for the implicit
6429 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00006430 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006431 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00006432 Object->Classify(Context),
6433 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006434 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006435 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006436 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00006437 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006438 return;
6439 }
6440
6441 // The first conversion is actually a user-defined conversion whose
6442 // first conversion is ObjectInit's standard conversion (which is
6443 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00006444 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006445 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00006446 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006447 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006448 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00006449 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00006450 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00006451 = Candidate.Conversions[0].UserDefined.Before;
6452 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6453
Mike Stump11289f42009-09-09 15:08:12 +00006454 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006455 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006456
6457 // (C++ 13.3.2p2): A candidate function having fewer than m
6458 // parameters is viable only if it has an ellipsis in its parameter
6459 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006460 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006461 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006462 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006463 return;
6464 }
6465
6466 // Function types don't have any default arguments, so just check if
6467 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006468 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006469 // Not enough arguments.
6470 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006471 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006472 return;
6473 }
6474
6475 // Determine the implicit conversion sequences for each of the
6476 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00006477 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006478 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006479 // (C++ 13.3.2p3): for F to be a viable function, there shall
6480 // exist for each argument an implicit conversion sequence
6481 // (13.3.3.1) that converts that argument to the corresponding
6482 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006483 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006484 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006485 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006486 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00006487 /*InOverloadResolution=*/false,
6488 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006489 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006490 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006491 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006492 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006493 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006494 }
6495 } else {
6496 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6497 // argument for which there is no corresponding parameter is
6498 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006499 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006500 }
6501 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006502
Craig Topper5fc8fc22014-08-27 06:28:36 +00006503 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006504 Candidate.Viable = false;
6505 Candidate.FailureKind = ovl_fail_enable_if;
6506 Candidate.DeductionFailure.Data = FailedAttr;
6507 return;
6508 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00006509}
6510
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006511/// \brief Add overload candidates for overloaded operators that are
6512/// member functions.
6513///
6514/// Add the overloaded operator candidates that are member functions
6515/// for the operator Op that was used in an operator expression such
6516/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6517/// CandidateSet will store the added overload candidates. (C++
6518/// [over.match.oper]).
6519void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6520 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00006521 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006522 OverloadCandidateSet& CandidateSet,
6523 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006524 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6525
6526 // C++ [over.match.oper]p3:
6527 // For a unary operator @ with an operand of a type whose
6528 // cv-unqualified version is T1, and for a binary operator @ with
6529 // a left operand of a type whose cv-unqualified version is T1 and
6530 // a right operand of a type whose cv-unqualified version is T2,
6531 // three sets of candidate functions, designated member
6532 // candidates, non-member candidates and built-in candidates, are
6533 // constructed as follows:
6534 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00006535
Richard Smith0feaf0c2013-04-20 12:41:22 +00006536 // -- If T1 is a complete class type or a class currently being
6537 // defined, the set of member candidates is the result of the
6538 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6539 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006540 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00006541 // Complete the type if it can be completed.
6542 RequireCompleteType(OpLoc, T1, 0);
6543 // If the type is neither complete nor being defined, bail out now.
6544 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006545 return;
Mike Stump11289f42009-09-09 15:08:12 +00006546
John McCall27b18f82009-11-17 02:14:36 +00006547 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6548 LookupQualifiedName(Operators, T1Rec->getDecl());
6549 Operators.suppressDiagnostics();
6550
Mike Stump11289f42009-09-09 15:08:12 +00006551 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006552 OperEnd = Operators.end();
6553 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00006554 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00006555 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola51629df2013-04-29 19:29:25 +00006556 Args[0]->Classify(Context),
Richard Smithe54c3072013-05-05 15:51:06 +00006557 Args.slice(1),
Douglas Gregor02824322011-01-26 19:30:28 +00006558 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006559 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00006560 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006561}
6562
Douglas Gregora11693b2008-11-12 17:17:38 +00006563/// AddBuiltinCandidate - Add a candidate for a built-in
6564/// operator. ResultTy and ParamTys are the result and parameter types
6565/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00006566/// arguments being passed to the candidate. IsAssignmentOperator
6567/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00006568/// operator. NumContextualBoolArguments is the number of arguments
6569/// (at the beginning of the argument list) that will be contextually
6570/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00006571void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smithe54c3072013-05-05 15:51:06 +00006572 ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00006573 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006574 bool IsAssignmentOperator,
6575 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00006576 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006577 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006578
Douglas Gregora11693b2008-11-12 17:17:38 +00006579 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00006580 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Craig Topperc3ec1492014-05-26 06:22:03 +00006581 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6582 Candidate.Function = nullptr;
Douglas Gregor1d248c52008-12-12 02:00:36 +00006583 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006584 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00006585 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smithe54c3072013-05-05 15:51:06 +00006586 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregora11693b2008-11-12 17:17:38 +00006587 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6588
6589 // Determine the implicit conversion sequences for each of the
6590 // arguments.
6591 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00006592 Candidate.ExplicitCallArguments = Args.size();
6593 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00006594 // C++ [over.match.oper]p4:
6595 // For the built-in assignment operators, conversions of the
6596 // left operand are restricted as follows:
6597 // -- no temporaries are introduced to hold the left operand, and
6598 // -- no user-defined conversions are applied to the left
6599 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00006600 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00006601 //
6602 // We block these conversions by turning off user-defined
6603 // conversions, since that is the only way that initialization of
6604 // a reference to a non-class type can occur from something that
6605 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006606 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006607 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006608 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006609 Candidate.Conversions[ArgIdx]
6610 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006611 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006612 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006613 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006614 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006615 /*InOverloadResolution=*/false,
6616 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006617 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006618 }
John McCall0d1da222010-01-12 00:44:57 +00006619 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006620 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006621 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006622 break;
6623 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006624 }
6625}
6626
Craig Toppercd7b0332013-07-01 06:29:40 +00006627namespace {
6628
Douglas Gregora11693b2008-11-12 17:17:38 +00006629/// BuiltinCandidateTypeSet - A set of types that will be used for the
6630/// candidate operator functions for built-in operators (C++
6631/// [over.built]). The types are separated into pointer types and
6632/// enumeration types.
6633class BuiltinCandidateTypeSet {
6634 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006635 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006636
6637 /// PointerTypes - The set of pointer types that will be used in the
6638 /// built-in candidates.
6639 TypeSet PointerTypes;
6640
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006641 /// MemberPointerTypes - The set of member pointer types that will be
6642 /// used in the built-in candidates.
6643 TypeSet MemberPointerTypes;
6644
Douglas Gregora11693b2008-11-12 17:17:38 +00006645 /// EnumerationTypes - The set of enumeration types that will be
6646 /// used in the built-in candidates.
6647 TypeSet EnumerationTypes;
6648
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006649 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006650 /// candidates.
6651 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006652
6653 /// \brief A flag indicating non-record types are viable candidates
6654 bool HasNonRecordTypes;
6655
6656 /// \brief A flag indicating whether either arithmetic or enumeration types
6657 /// were present in the candidate set.
6658 bool HasArithmeticOrEnumeralTypes;
6659
Douglas Gregor80af3132011-05-21 23:15:46 +00006660 /// \brief A flag indicating whether the nullptr type was present in the
6661 /// candidate set.
6662 bool HasNullPtrType;
6663
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006664 /// Sema - The semantic analysis instance where we are building the
6665 /// candidate type set.
6666 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006667
Douglas Gregora11693b2008-11-12 17:17:38 +00006668 /// Context - The AST context in which we will build the type sets.
6669 ASTContext &Context;
6670
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006671 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6672 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006673 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006674
6675public:
6676 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006677 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006678
Mike Stump11289f42009-09-09 15:08:12 +00006679 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006680 : HasNonRecordTypes(false),
6681 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006682 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006683 SemaRef(SemaRef),
6684 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006685
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006686 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006687 SourceLocation Loc,
6688 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006689 bool AllowExplicitConversions,
6690 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006691
6692 /// pointer_begin - First pointer type found;
6693 iterator pointer_begin() { return PointerTypes.begin(); }
6694
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006695 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006696 iterator pointer_end() { return PointerTypes.end(); }
6697
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006698 /// member_pointer_begin - First member pointer type found;
6699 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6700
6701 /// member_pointer_end - Past the last member pointer type found;
6702 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6703
Douglas Gregora11693b2008-11-12 17:17:38 +00006704 /// enumeration_begin - First enumeration type found;
6705 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6706
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006707 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006708 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006709
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006710 iterator vector_begin() { return VectorTypes.begin(); }
6711 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006712
6713 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6714 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006715 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006716};
6717
Craig Toppercd7b0332013-07-01 06:29:40 +00006718} // end anonymous namespace
6719
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006720/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006721/// the set of pointer types along with any more-qualified variants of
6722/// that type. For example, if @p Ty is "int const *", this routine
6723/// will add "int const *", "int const volatile *", "int const
6724/// restrict *", and "int const volatile restrict *" to the set of
6725/// pointer types. Returns true if the add of @p Ty itself succeeded,
6726/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006727///
6728/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006729bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006730BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6731 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006732
Douglas Gregora11693b2008-11-12 17:17:38 +00006733 // Insert this type.
David Blaikie82e95a32014-11-19 07:49:47 +00006734 if (!PointerTypes.insert(Ty).second)
Douglas Gregora11693b2008-11-12 17:17:38 +00006735 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006736
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006737 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006738 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006739 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006740 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006741 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6742 PointeeTy = PTy->getPointeeType();
6743 buildObjCPtr = true;
6744 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006745 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00006746 }
6747
Sebastian Redl4990a632009-11-18 20:39:26 +00006748 // Don't add qualified variants of arrays. For one, they're not allowed
6749 // (the qualifier would sink to the element type), and for another, the
6750 // only overload situation where it matters is subscript or pointer +- int,
6751 // and those shouldn't have qualifier variants anyway.
6752 if (PointeeTy->isArrayType())
6753 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006754
John McCall8ccfcb52009-09-24 19:53:00 +00006755 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006756 bool hasVolatile = VisibleQuals.hasVolatile();
6757 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006758
John McCall8ccfcb52009-09-24 19:53:00 +00006759 // Iterate through all strict supersets of BaseCVR.
6760 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6761 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006762 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006763 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006764
6765 // Skip over restrict if no restrict found anywhere in the types, or if
6766 // the type cannot be restrict-qualified.
6767 if ((CVR & Qualifiers::Restrict) &&
6768 (!hasRestrict ||
6769 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6770 continue;
6771
6772 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00006773 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006774
6775 // Build qualified pointer type.
6776 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006777 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00006778 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006779 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00006780 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6781
6782 // Insert qualified pointer type.
6783 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00006784 }
6785
6786 return true;
6787}
6788
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006789/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6790/// to the set of pointer types along with any more-qualified variants of
6791/// that type. For example, if @p Ty is "int const *", this routine
6792/// will add "int const *", "int const volatile *", "int const
6793/// restrict *", and "int const volatile restrict *" to the set of
6794/// pointer types. Returns true if the add of @p Ty itself succeeded,
6795/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006796///
6797/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006798bool
6799BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6800 QualType Ty) {
6801 // Insert this type.
David Blaikie82e95a32014-11-19 07:49:47 +00006802 if (!MemberPointerTypes.insert(Ty).second)
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006803 return false;
6804
John McCall8ccfcb52009-09-24 19:53:00 +00006805 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6806 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006807
John McCall8ccfcb52009-09-24 19:53:00 +00006808 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006809 // Don't add qualified variants of arrays. For one, they're not allowed
6810 // (the qualifier would sink to the element type), and for another, the
6811 // only overload situation where it matters is subscript or pointer +- int,
6812 // and those shouldn't have qualifier variants anyway.
6813 if (PointeeTy->isArrayType())
6814 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006815 const Type *ClassTy = PointerTy->getClass();
6816
6817 // Iterate through all strict supersets of the pointee type's CVR
6818 // qualifiers.
6819 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6820 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6821 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006822
John McCall8ccfcb52009-09-24 19:53:00 +00006823 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006824 MemberPointerTypes.insert(
6825 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006826 }
6827
6828 return true;
6829}
6830
Douglas Gregora11693b2008-11-12 17:17:38 +00006831/// AddTypesConvertedFrom - Add each of the types to which the type @p
6832/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006833/// primarily interested in pointer types and enumeration types. We also
6834/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006835/// AllowUserConversions is true if we should look at the conversion
6836/// functions of a class type, and AllowExplicitConversions if we
6837/// should also include the explicit conversion functions of a class
6838/// type.
Mike Stump11289f42009-09-09 15:08:12 +00006839void
Douglas Gregor5fb53972009-01-14 15:45:31 +00006840BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006841 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006842 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006843 bool AllowExplicitConversions,
6844 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006845 // Only deal with canonical types.
6846 Ty = Context.getCanonicalType(Ty);
6847
6848 // Look through reference types; they aren't part of the type of an
6849 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006850 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00006851 Ty = RefTy->getPointeeType();
6852
John McCall33ddac02011-01-19 10:06:00 +00006853 // If we're dealing with an array type, decay to the pointer.
6854 if (Ty->isArrayType())
6855 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6856
6857 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006858 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00006859
Chandler Carruth00a38332010-12-13 01:44:01 +00006860 // Flag if we ever add a non-record type.
6861 const RecordType *TyRec = Ty->getAs<RecordType>();
6862 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6863
Chandler Carruth00a38332010-12-13 01:44:01 +00006864 // Flag if we encounter an arithmetic type.
6865 HasArithmeticOrEnumeralTypes =
6866 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6867
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006868 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6869 PointerTypes.insert(Ty);
6870 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006871 // Insert our type, and its more-qualified variants, into the set
6872 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006873 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00006874 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006875 } else if (Ty->isMemberPointerType()) {
6876 // Member pointers are far easier, since the pointee can't be converted.
6877 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6878 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00006879 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006880 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00006881 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006882 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006883 // We treat vector types as arithmetic types in many contexts as an
6884 // extension.
6885 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006886 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00006887 } else if (Ty->isNullPtrType()) {
6888 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00006889 } else if (AllowUserConversions && TyRec) {
6890 // No conversion functions in incomplete types.
6891 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6892 return;
Mike Stump11289f42009-09-09 15:08:12 +00006893
Chandler Carruth00a38332010-12-13 01:44:01 +00006894 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006895 std::pair<CXXRecordDecl::conversion_iterator,
6896 CXXRecordDecl::conversion_iterator>
6897 Conversions = ClassDecl->getVisibleConversionFunctions();
6898 for (CXXRecordDecl::conversion_iterator
6899 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006900 NamedDecl *D = I.getDecl();
6901 if (isa<UsingShadowDecl>(D))
6902 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00006903
Chandler Carruth00a38332010-12-13 01:44:01 +00006904 // Skip conversion function templates; they don't tell us anything
6905 // about which builtin types we can convert to.
6906 if (isa<FunctionTemplateDecl>(D))
6907 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006908
Chandler Carruth00a38332010-12-13 01:44:01 +00006909 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6910 if (AllowExplicitConversions || !Conv->isExplicit()) {
6911 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6912 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006913 }
6914 }
6915 }
6916}
6917
Douglas Gregor84605ae2009-08-24 13:43:27 +00006918/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6919/// the volatile- and non-volatile-qualified assignment operators for the
6920/// given type to the candidate set.
6921static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6922 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00006923 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006924 OverloadCandidateSet &CandidateSet) {
6925 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00006926
Douglas Gregor84605ae2009-08-24 13:43:27 +00006927 // T& operator=(T&, T)
6928 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6929 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00006930 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006931 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00006932
Douglas Gregor84605ae2009-08-24 13:43:27 +00006933 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6934 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00006935 ParamTypes[0]
6936 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00006937 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00006938 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00006939 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00006940 }
6941}
Mike Stump11289f42009-09-09 15:08:12 +00006942
Sebastian Redl1054fae2009-10-25 17:03:50 +00006943/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6944/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006945static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6946 Qualifiers VRQuals;
6947 const RecordType *TyRec;
6948 if (const MemberPointerType *RHSMPType =
6949 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00006950 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006951 else
6952 TyRec = ArgExpr->getType()->getAs<RecordType>();
6953 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006954 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006955 VRQuals.addVolatile();
6956 VRQuals.addRestrict();
6957 return VRQuals;
6958 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006959
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006960 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00006961 if (!ClassDecl->hasDefinition())
6962 return VRQuals;
6963
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006964 std::pair<CXXRecordDecl::conversion_iterator,
6965 CXXRecordDecl::conversion_iterator>
6966 Conversions = ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006967
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006968 for (CXXRecordDecl::conversion_iterator
6969 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00006970 NamedDecl *D = I.getDecl();
6971 if (isa<UsingShadowDecl>(D))
6972 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6973 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006974 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6975 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6976 CanTy = ResTypeRef->getPointeeType();
6977 // Need to go down the pointer/mempointer chain and add qualifiers
6978 // as see them.
6979 bool done = false;
6980 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006981 if (CanTy.isRestrictQualified())
6982 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006983 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6984 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006985 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006986 CanTy->getAs<MemberPointerType>())
6987 CanTy = ResTypeMPtr->getPointeeType();
6988 else
6989 done = true;
6990 if (CanTy.isVolatileQualified())
6991 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006992 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6993 return VRQuals;
6994 }
6995 }
6996 }
6997 return VRQuals;
6998}
John McCall52872982010-11-13 05:51:15 +00006999
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007000namespace {
John McCall52872982010-11-13 05:51:15 +00007001
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007002/// \brief Helper class to manage the addition of builtin operator overload
7003/// candidates. It provides shared state and utility methods used throughout
7004/// the process, as well as a helper method to add each group of builtin
7005/// operator overloads from the standard to a candidate set.
7006class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007007 // Common instance state available to all overload candidate addition methods.
7008 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00007009 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007010 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00007011 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007012 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007013 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007014
Chandler Carruthc6586e52010-12-12 10:35:00 +00007015 // Define some constants used to index and iterate over the arithemetic types
7016 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00007017 // The "promoted arithmetic types" are the arithmetic
7018 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00007019 static const unsigned FirstIntegralType = 3;
Richard Smith521ecc12012-06-10 08:00:26 +00007020 static const unsigned LastIntegralType = 20;
John McCall52872982010-11-13 05:51:15 +00007021 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith521ecc12012-06-10 08:00:26 +00007022 LastPromotedIntegralType = 11;
John McCall52872982010-11-13 05:51:15 +00007023 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith521ecc12012-06-10 08:00:26 +00007024 LastPromotedArithmeticType = 11;
7025 static const unsigned NumArithmeticTypes = 20;
John McCall52872982010-11-13 05:51:15 +00007026
Chandler Carruthc6586e52010-12-12 10:35:00 +00007027 /// \brief Get the canonical type for a given arithmetic type index.
7028 CanQualType getArithmeticType(unsigned index) {
7029 assert(index < NumArithmeticTypes);
7030 static CanQualType ASTContext::* const
7031 ArithmeticTypes[NumArithmeticTypes] = {
7032 // Start of promoted types.
7033 &ASTContext::FloatTy,
7034 &ASTContext::DoubleTy,
7035 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00007036
Chandler Carruthc6586e52010-12-12 10:35:00 +00007037 // Start of integral types.
7038 &ASTContext::IntTy,
7039 &ASTContext::LongTy,
7040 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007041 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007042 &ASTContext::UnsignedIntTy,
7043 &ASTContext::UnsignedLongTy,
7044 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007045 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007046 // End of promoted types.
7047
7048 &ASTContext::BoolTy,
7049 &ASTContext::CharTy,
7050 &ASTContext::WCharTy,
7051 &ASTContext::Char16Ty,
7052 &ASTContext::Char32Ty,
7053 &ASTContext::SignedCharTy,
7054 &ASTContext::ShortTy,
7055 &ASTContext::UnsignedCharTy,
7056 &ASTContext::UnsignedShortTy,
7057 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00007058 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00007059 };
7060 return S.Context.*ArithmeticTypes[index];
7061 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007062
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007063 /// \brief Gets the canonical type resulting from the usual arithemetic
7064 /// converions for the given arithmetic types.
7065 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7066 // Accelerator table for performing the usual arithmetic conversions.
7067 // The rules are basically:
7068 // - if either is floating-point, use the wider floating-point
7069 // - if same signedness, use the higher rank
7070 // - if same size, use unsigned of the higher rank
7071 // - use the larger type
7072 // These rules, together with the axiom that higher ranks are
7073 // never smaller, are sufficient to precompute all of these results
7074 // *except* when dealing with signed types of higher rank.
7075 // (we could precompute SLL x UI for all known platforms, but it's
7076 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00007077 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007078 enum PromotedType {
Richard Smith521ecc12012-06-10 08:00:26 +00007079 Dep=-1,
7080 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007081 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00007082 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007083 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00007084/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7085/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7086/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7087/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7088/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7089/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7090/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7091/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7092/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7093/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7094/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007095 };
7096
7097 assert(L < LastPromotedArithmeticType);
7098 assert(R < LastPromotedArithmeticType);
7099 int Idx = ConversionsTable[L][R];
7100
7101 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007102 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007103
7104 // Slow path: we need to compare widths.
7105 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007106 CanQualType LT = getArithmeticType(L),
7107 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007108 unsigned LW = S.Context.getIntWidth(LT),
7109 RW = S.Context.getIntWidth(RT);
7110
7111 // If they're different widths, use the signed type.
7112 if (LW > RW) return LT;
7113 else if (LW < RW) return RT;
7114
7115 // Otherwise, use the unsigned type of the signed type's rank.
7116 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7117 assert(L == SLL || R == SLL);
7118 return S.Context.UnsignedLongLongTy;
7119 }
7120
Chandler Carruth5659c0c2010-12-12 09:22:45 +00007121 /// \brief Helper method to factor out the common pattern of adding overloads
7122 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007123 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007124 bool HasVolatile,
7125 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007126 QualType ParamTypes[2] = {
7127 S.Context.getLValueReferenceType(CandidateTy),
7128 S.Context.IntTy
7129 };
7130
7131 // Non-volatile version.
Richard Smithe54c3072013-05-05 15:51:06 +00007132 if (Args.size() == 1)
7133 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007134 else
Richard Smithe54c3072013-05-05 15:51:06 +00007135 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007136
7137 // Use a heuristic to reduce number of builtin candidates in the set:
7138 // add volatile version only if there are conversions to a volatile type.
7139 if (HasVolatile) {
7140 ParamTypes[0] =
7141 S.Context.getLValueReferenceType(
7142 S.Context.getVolatileType(CandidateTy));
Richard Smithe54c3072013-05-05 15:51:06 +00007143 if (Args.size() == 1)
7144 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007145 else
Richard Smithe54c3072013-05-05 15:51:06 +00007146 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007147 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007148
7149 // Add restrict version only if there are conversions to a restrict type
7150 // and our candidate type is a non-restrict-qualified pointer.
7151 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7152 !CandidateTy.isRestrictQualified()) {
7153 ParamTypes[0]
7154 = S.Context.getLValueReferenceType(
7155 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smithe54c3072013-05-05 15:51:06 +00007156 if (Args.size() == 1)
7157 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007158 else
Richard Smithe54c3072013-05-05 15:51:06 +00007159 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007160
7161 if (HasVolatile) {
7162 ParamTypes[0]
7163 = S.Context.getLValueReferenceType(
7164 S.Context.getCVRQualifiedType(CandidateTy,
7165 (Qualifiers::Volatile |
7166 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007167 if (Args.size() == 1)
7168 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007169 else
Richard Smithe54c3072013-05-05 15:51:06 +00007170 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007171 }
7172 }
7173
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007174 }
7175
7176public:
7177 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007178 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007179 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007180 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007181 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007182 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007183 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007184 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007185 HasArithmeticOrEnumeralCandidateType(
7186 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007187 CandidateTypes(CandidateTypes),
7188 CandidateSet(CandidateSet) {
7189 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007190 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007191 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007192 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007193 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007194 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007195 assert(getArithmeticType(FirstPromotedArithmeticType)
7196 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007197 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007198 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007199 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007200 "Invalid last promoted arithmetic type");
7201 }
7202
7203 // C++ [over.built]p3:
7204 //
7205 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7206 // is either volatile or empty, there exist candidate operator
7207 // functions of the form
7208 //
7209 // VQ T& operator++(VQ T&);
7210 // T operator++(VQ T&, int);
7211 //
7212 // C++ [over.built]p4:
7213 //
7214 // For every pair (T, VQ), where T is an arithmetic type other
7215 // than bool, and VQ is either volatile or empty, there exist
7216 // candidate operator functions of the form
7217 //
7218 // VQ T& operator--(VQ T&);
7219 // T operator--(VQ T&, int);
7220 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007221 if (!HasArithmeticOrEnumeralCandidateType)
7222 return;
7223
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007224 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7225 Arith < NumArithmeticTypes; ++Arith) {
7226 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007227 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007228 VisibleTypeConversionsQuals.hasVolatile(),
7229 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007230 }
7231 }
7232
7233 // C++ [over.built]p5:
7234 //
7235 // For every pair (T, VQ), where T is a cv-qualified or
7236 // cv-unqualified object type, and VQ is either volatile or
7237 // empty, there exist candidate operator functions of the form
7238 //
7239 // T*VQ& operator++(T*VQ&);
7240 // T*VQ& operator--(T*VQ&);
7241 // T* operator++(T*VQ&, int);
7242 // T* operator--(T*VQ&, int);
7243 void addPlusPlusMinusMinusPointerOverloads() {
7244 for (BuiltinCandidateTypeSet::iterator
7245 Ptr = CandidateTypes[0].pointer_begin(),
7246 PtrEnd = CandidateTypes[0].pointer_end();
7247 Ptr != PtrEnd; ++Ptr) {
7248 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007249 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007250 continue;
7251
7252 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007253 (!(*Ptr).isVolatileQualified() &&
7254 VisibleTypeConversionsQuals.hasVolatile()),
7255 (!(*Ptr).isRestrictQualified() &&
7256 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007257 }
7258 }
7259
7260 // C++ [over.built]p6:
7261 // For every cv-qualified or cv-unqualified object type T, there
7262 // exist candidate operator functions of the form
7263 //
7264 // T& operator*(T*);
7265 //
7266 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007267 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007268 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007269 // T& operator*(T*);
7270 void addUnaryStarPointerOverloads() {
7271 for (BuiltinCandidateTypeSet::iterator
7272 Ptr = CandidateTypes[0].pointer_begin(),
7273 PtrEnd = CandidateTypes[0].pointer_end();
7274 Ptr != PtrEnd; ++Ptr) {
7275 QualType ParamTy = *Ptr;
7276 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007277 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7278 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007279
Douglas Gregor02824322011-01-26 19:30:28 +00007280 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7281 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7282 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007283
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007284 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smithe54c3072013-05-05 15:51:06 +00007285 &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007286 }
7287 }
7288
7289 // C++ [over.built]p9:
7290 // For every promoted arithmetic type T, there exist candidate
7291 // operator functions of the form
7292 //
7293 // T operator+(T);
7294 // T operator-(T);
7295 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007296 if (!HasArithmeticOrEnumeralCandidateType)
7297 return;
7298
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007299 for (unsigned Arith = FirstPromotedArithmeticType;
7300 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007301 QualType ArithTy = getArithmeticType(Arith);
Richard Smithe54c3072013-05-05 15:51:06 +00007302 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007303 }
7304
7305 // Extension: We also add these operators for vector types.
7306 for (BuiltinCandidateTypeSet::iterator
7307 Vec = CandidateTypes[0].vector_begin(),
7308 VecEnd = CandidateTypes[0].vector_end();
7309 Vec != VecEnd; ++Vec) {
7310 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007311 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007312 }
7313 }
7314
7315 // C++ [over.built]p8:
7316 // For every type T, there exist candidate operator functions of
7317 // the form
7318 //
7319 // T* operator+(T*);
7320 void addUnaryPlusPointerOverloads() {
7321 for (BuiltinCandidateTypeSet::iterator
7322 Ptr = CandidateTypes[0].pointer_begin(),
7323 PtrEnd = CandidateTypes[0].pointer_end();
7324 Ptr != PtrEnd; ++Ptr) {
7325 QualType ParamTy = *Ptr;
Richard Smithe54c3072013-05-05 15:51:06 +00007326 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007327 }
7328 }
7329
7330 // C++ [over.built]p10:
7331 // For every promoted integral type T, there exist candidate
7332 // operator functions of the form
7333 //
7334 // T operator~(T);
7335 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007336 if (!HasArithmeticOrEnumeralCandidateType)
7337 return;
7338
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007339 for (unsigned Int = FirstPromotedIntegralType;
7340 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007341 QualType IntTy = getArithmeticType(Int);
Richard Smithe54c3072013-05-05 15:51:06 +00007342 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007343 }
7344
7345 // Extension: We also add this operator for vector types.
7346 for (BuiltinCandidateTypeSet::iterator
7347 Vec = CandidateTypes[0].vector_begin(),
7348 VecEnd = CandidateTypes[0].vector_end();
7349 Vec != VecEnd; ++Vec) {
7350 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007351 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007352 }
7353 }
7354
7355 // C++ [over.match.oper]p16:
7356 // For every pointer to member type T, there exist candidate operator
7357 // functions of the form
7358 //
7359 // bool operator==(T,T);
7360 // bool operator!=(T,T);
7361 void addEqualEqualOrNotEqualMemberPointerOverloads() {
7362 /// Set of (canonical) types that we've already handled.
7363 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7364
Richard Smithe54c3072013-05-05 15:51:06 +00007365 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007366 for (BuiltinCandidateTypeSet::iterator
7367 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7368 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7369 MemPtr != MemPtrEnd;
7370 ++MemPtr) {
7371 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007372 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007373 continue;
7374
7375 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007376 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007377 }
7378 }
7379 }
7380
7381 // C++ [over.built]p15:
7382 //
Douglas Gregor80af3132011-05-21 23:15:46 +00007383 // For every T, where T is an enumeration type, a pointer type, or
7384 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007385 //
7386 // bool operator<(T, T);
7387 // bool operator>(T, T);
7388 // bool operator<=(T, T);
7389 // bool operator>=(T, T);
7390 // bool operator==(T, T);
7391 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007392 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007393 // C++ [over.match.oper]p3:
7394 // [...]the built-in candidates include all of the candidate operator
7395 // functions defined in 13.6 that, compared to the given operator, [...]
7396 // do not have the same parameter-type-list as any non-template non-member
7397 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007398 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007399 // Note that in practice, this only affects enumeration types because there
7400 // aren't any built-in candidates of record type, and a user-defined operator
7401 // must have an operand of record or enumeration type. Also, the only other
7402 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007403 // cannot be overloaded for enumeration types, so this is the only place
7404 // where we must suppress candidates like this.
7405 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7406 UserDefinedBinaryOperators;
7407
Richard Smithe54c3072013-05-05 15:51:06 +00007408 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007409 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7410 CandidateTypes[ArgIdx].enumeration_end()) {
7411 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7412 CEnd = CandidateSet.end();
7413 C != CEnd; ++C) {
7414 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7415 continue;
7416
Eli Friedman14f082b2012-09-18 21:52:24 +00007417 if (C->Function->isFunctionTemplateSpecialization())
7418 continue;
7419
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007420 QualType FirstParamType =
7421 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7422 QualType SecondParamType =
7423 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7424
7425 // Skip if either parameter isn't of enumeral type.
7426 if (!FirstParamType->isEnumeralType() ||
7427 !SecondParamType->isEnumeralType())
7428 continue;
7429
7430 // Add this operator to the set of known user-defined operators.
7431 UserDefinedBinaryOperators.insert(
7432 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7433 S.Context.getCanonicalType(SecondParamType)));
7434 }
7435 }
7436 }
7437
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007438 /// Set of (canonical) types that we've already handled.
7439 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7440
Richard Smithe54c3072013-05-05 15:51:06 +00007441 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007442 for (BuiltinCandidateTypeSet::iterator
7443 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7444 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7445 Ptr != PtrEnd; ++Ptr) {
7446 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007447 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007448 continue;
7449
7450 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007451 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007452 }
7453 for (BuiltinCandidateTypeSet::iterator
7454 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7455 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7456 Enum != EnumEnd; ++Enum) {
7457 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7458
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007459 // Don't add the same builtin candidate twice, or if a user defined
7460 // candidate exists.
David Blaikie82e95a32014-11-19 07:49:47 +00007461 if (!AddedTypes.insert(CanonType).second ||
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007462 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7463 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007464 continue;
7465
7466 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007467 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007468 }
Douglas Gregor80af3132011-05-21 23:15:46 +00007469
7470 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7471 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
David Blaikie82e95a32014-11-19 07:49:47 +00007472 if (AddedTypes.insert(NullPtrTy).second &&
Richard Smithe54c3072013-05-05 15:51:06 +00007473 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor80af3132011-05-21 23:15:46 +00007474 NullPtrTy))) {
7475 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007476 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor80af3132011-05-21 23:15:46 +00007477 CandidateSet);
7478 }
7479 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007480 }
7481 }
7482
7483 // C++ [over.built]p13:
7484 //
7485 // For every cv-qualified or cv-unqualified object type T
7486 // there exist candidate operator functions of the form
7487 //
7488 // T* operator+(T*, ptrdiff_t);
7489 // T& operator[](T*, ptrdiff_t); [BELOW]
7490 // T* operator-(T*, ptrdiff_t);
7491 // T* operator+(ptrdiff_t, T*);
7492 // T& operator[](ptrdiff_t, T*); [BELOW]
7493 //
7494 // C++ [over.built]p14:
7495 //
7496 // For every T, where T is a pointer to object type, there
7497 // exist candidate operator functions of the form
7498 //
7499 // ptrdiff_t operator-(T, T);
7500 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7501 /// Set of (canonical) types that we've already handled.
7502 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7503
7504 for (int Arg = 0; Arg < 2; ++Arg) {
7505 QualType AsymetricParamTypes[2] = {
7506 S.Context.getPointerDiffType(),
7507 S.Context.getPointerDiffType(),
7508 };
7509 for (BuiltinCandidateTypeSet::iterator
7510 Ptr = CandidateTypes[Arg].pointer_begin(),
7511 PtrEnd = CandidateTypes[Arg].pointer_end();
7512 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00007513 QualType PointeeTy = (*Ptr)->getPointeeType();
7514 if (!PointeeTy->isObjectType())
7515 continue;
7516
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007517 AsymetricParamTypes[Arg] = *Ptr;
7518 if (Arg == 0 || Op == OO_Plus) {
7519 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7520 // T* operator+(ptrdiff_t, T*);
Richard Smithe54c3072013-05-05 15:51:06 +00007521 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007522 }
7523 if (Op == OO_Minus) {
7524 // ptrdiff_t operator-(T, T);
David Blaikie82e95a32014-11-19 07:49:47 +00007525 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007526 continue;
7527
7528 QualType ParamTypes[2] = { *Ptr, *Ptr };
7529 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smithe54c3072013-05-05 15:51:06 +00007530 Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007531 }
7532 }
7533 }
7534 }
7535
7536 // C++ [over.built]p12:
7537 //
7538 // For every pair of promoted arithmetic types L and R, there
7539 // exist candidate operator functions of the form
7540 //
7541 // LR operator*(L, R);
7542 // LR operator/(L, R);
7543 // LR operator+(L, R);
7544 // LR operator-(L, R);
7545 // bool operator<(L, R);
7546 // bool operator>(L, R);
7547 // bool operator<=(L, R);
7548 // bool operator>=(L, R);
7549 // bool operator==(L, R);
7550 // bool operator!=(L, R);
7551 //
7552 // where LR is the result of the usual arithmetic conversions
7553 // between types L and R.
7554 //
7555 // C++ [over.built]p24:
7556 //
7557 // For every pair of promoted arithmetic types L and R, there exist
7558 // candidate operator functions of the form
7559 //
7560 // LR operator?(bool, L, R);
7561 //
7562 // where LR is the result of the usual arithmetic conversions
7563 // between types L and R.
7564 // Our candidates ignore the first parameter.
7565 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007566 if (!HasArithmeticOrEnumeralCandidateType)
7567 return;
7568
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007569 for (unsigned Left = FirstPromotedArithmeticType;
7570 Left < LastPromotedArithmeticType; ++Left) {
7571 for (unsigned Right = FirstPromotedArithmeticType;
7572 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007573 QualType LandR[2] = { getArithmeticType(Left),
7574 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007575 QualType Result =
7576 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007577 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007578 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007579 }
7580 }
7581
7582 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7583 // conditional operator for vector types.
7584 for (BuiltinCandidateTypeSet::iterator
7585 Vec1 = CandidateTypes[0].vector_begin(),
7586 Vec1End = CandidateTypes[0].vector_end();
7587 Vec1 != Vec1End; ++Vec1) {
7588 for (BuiltinCandidateTypeSet::iterator
7589 Vec2 = CandidateTypes[1].vector_begin(),
7590 Vec2End = CandidateTypes[1].vector_end();
7591 Vec2 != Vec2End; ++Vec2) {
7592 QualType LandR[2] = { *Vec1, *Vec2 };
7593 QualType Result = S.Context.BoolTy;
7594 if (!isComparison) {
7595 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7596 Result = *Vec1;
7597 else
7598 Result = *Vec2;
7599 }
7600
Richard Smithe54c3072013-05-05 15:51:06 +00007601 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007602 }
7603 }
7604 }
7605
7606 // C++ [over.built]p17:
7607 //
7608 // For every pair of promoted integral types L and R, there
7609 // exist candidate operator functions of the form
7610 //
7611 // LR operator%(L, R);
7612 // LR operator&(L, R);
7613 // LR operator^(L, R);
7614 // LR operator|(L, R);
7615 // L operator<<(L, R);
7616 // L operator>>(L, R);
7617 //
7618 // where LR is the result of the usual arithmetic conversions
7619 // between types L and R.
7620 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007621 if (!HasArithmeticOrEnumeralCandidateType)
7622 return;
7623
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007624 for (unsigned Left = FirstPromotedIntegralType;
7625 Left < LastPromotedIntegralType; ++Left) {
7626 for (unsigned Right = FirstPromotedIntegralType;
7627 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007628 QualType LandR[2] = { getArithmeticType(Left),
7629 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007630 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7631 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007632 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007633 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007634 }
7635 }
7636 }
7637
7638 // C++ [over.built]p20:
7639 //
7640 // For every pair (T, VQ), where T is an enumeration or
7641 // pointer to member type and VQ is either volatile or
7642 // empty, there exist candidate operator functions of the form
7643 //
7644 // VQ T& operator=(VQ T&, T);
7645 void addAssignmentMemberPointerOrEnumeralOverloads() {
7646 /// Set of (canonical) types that we've already handled.
7647 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7648
7649 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7650 for (BuiltinCandidateTypeSet::iterator
7651 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7652 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7653 Enum != EnumEnd; ++Enum) {
David Blaikie82e95a32014-11-19 07:49:47 +00007654 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007655 continue;
7656
Richard Smithe54c3072013-05-05 15:51:06 +00007657 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007658 }
7659
7660 for (BuiltinCandidateTypeSet::iterator
7661 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7662 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7663 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00007664 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007665 continue;
7666
Richard Smithe54c3072013-05-05 15:51:06 +00007667 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007668 }
7669 }
7670 }
7671
7672 // C++ [over.built]p19:
7673 //
7674 // For every pair (T, VQ), where T is any type and VQ is either
7675 // volatile or empty, there exist candidate operator functions
7676 // of the form
7677 //
7678 // T*VQ& operator=(T*VQ&, T*);
7679 //
7680 // C++ [over.built]p21:
7681 //
7682 // For every pair (T, VQ), where T is a cv-qualified or
7683 // cv-unqualified object type and VQ is either volatile or
7684 // empty, there exist candidate operator functions of the form
7685 //
7686 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7687 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7688 void addAssignmentPointerOverloads(bool isEqualOp) {
7689 /// Set of (canonical) types that we've already handled.
7690 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7691
7692 for (BuiltinCandidateTypeSet::iterator
7693 Ptr = CandidateTypes[0].pointer_begin(),
7694 PtrEnd = CandidateTypes[0].pointer_end();
7695 Ptr != PtrEnd; ++Ptr) {
7696 // If this is operator=, keep track of the builtin candidates we added.
7697 if (isEqualOp)
7698 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007699 else if (!(*Ptr)->getPointeeType()->isObjectType())
7700 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007701
7702 // non-volatile version
7703 QualType ParamTypes[2] = {
7704 S.Context.getLValueReferenceType(*Ptr),
7705 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7706 };
Richard Smithe54c3072013-05-05 15:51:06 +00007707 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007708 /*IsAssigmentOperator=*/ isEqualOp);
7709
Douglas Gregor5bee2582012-06-04 00:15:09 +00007710 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7711 VisibleTypeConversionsQuals.hasVolatile();
7712 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007713 // volatile version
7714 ParamTypes[0] =
7715 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007716 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007717 /*IsAssigmentOperator=*/isEqualOp);
7718 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007719
7720 if (!(*Ptr).isRestrictQualified() &&
7721 VisibleTypeConversionsQuals.hasRestrict()) {
7722 // restrict version
7723 ParamTypes[0]
7724 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007725 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007726 /*IsAssigmentOperator=*/isEqualOp);
7727
7728 if (NeedVolatile) {
7729 // volatile restrict version
7730 ParamTypes[0]
7731 = S.Context.getLValueReferenceType(
7732 S.Context.getCVRQualifiedType(*Ptr,
7733 (Qualifiers::Volatile |
7734 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007735 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007736 /*IsAssigmentOperator=*/isEqualOp);
7737 }
7738 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007739 }
7740
7741 if (isEqualOp) {
7742 for (BuiltinCandidateTypeSet::iterator
7743 Ptr = CandidateTypes[1].pointer_begin(),
7744 PtrEnd = CandidateTypes[1].pointer_end();
7745 Ptr != PtrEnd; ++Ptr) {
7746 // Make sure we don't add the same candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007747 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007748 continue;
7749
Chandler Carruth8e543b32010-12-12 08:17:55 +00007750 QualType ParamTypes[2] = {
7751 S.Context.getLValueReferenceType(*Ptr),
7752 *Ptr,
7753 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007754
7755 // non-volatile version
Richard Smithe54c3072013-05-05 15:51:06 +00007756 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007757 /*IsAssigmentOperator=*/true);
7758
Douglas Gregor5bee2582012-06-04 00:15:09 +00007759 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7760 VisibleTypeConversionsQuals.hasVolatile();
7761 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007762 // volatile version
7763 ParamTypes[0] =
7764 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007765 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7766 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007767 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007768
7769 if (!(*Ptr).isRestrictQualified() &&
7770 VisibleTypeConversionsQuals.hasRestrict()) {
7771 // restrict version
7772 ParamTypes[0]
7773 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007774 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7775 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007776
7777 if (NeedVolatile) {
7778 // volatile restrict version
7779 ParamTypes[0]
7780 = S.Context.getLValueReferenceType(
7781 S.Context.getCVRQualifiedType(*Ptr,
7782 (Qualifiers::Volatile |
7783 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007784 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7785 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007786 }
7787 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007788 }
7789 }
7790 }
7791
7792 // C++ [over.built]p18:
7793 //
7794 // For every triple (L, VQ, R), where L is an arithmetic type,
7795 // VQ is either volatile or empty, and R is a promoted
7796 // arithmetic type, there exist candidate operator functions of
7797 // the form
7798 //
7799 // VQ L& operator=(VQ L&, R);
7800 // VQ L& operator*=(VQ L&, R);
7801 // VQ L& operator/=(VQ L&, R);
7802 // VQ L& operator+=(VQ L&, R);
7803 // VQ L& operator-=(VQ L&, R);
7804 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007805 if (!HasArithmeticOrEnumeralCandidateType)
7806 return;
7807
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007808 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7809 for (unsigned Right = FirstPromotedArithmeticType;
7810 Right < LastPromotedArithmeticType; ++Right) {
7811 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007812 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007813
7814 // Add this built-in operator as a candidate (VQ is empty).
7815 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007816 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007817 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007818 /*IsAssigmentOperator=*/isEqualOp);
7819
7820 // Add this built-in operator as a candidate (VQ is 'volatile').
7821 if (VisibleTypeConversionsQuals.hasVolatile()) {
7822 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007823 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007824 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007825 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007826 /*IsAssigmentOperator=*/isEqualOp);
7827 }
7828 }
7829 }
7830
7831 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7832 for (BuiltinCandidateTypeSet::iterator
7833 Vec1 = CandidateTypes[0].vector_begin(),
7834 Vec1End = CandidateTypes[0].vector_end();
7835 Vec1 != Vec1End; ++Vec1) {
7836 for (BuiltinCandidateTypeSet::iterator
7837 Vec2 = CandidateTypes[1].vector_begin(),
7838 Vec2End = CandidateTypes[1].vector_end();
7839 Vec2 != Vec2End; ++Vec2) {
7840 QualType ParamTypes[2];
7841 ParamTypes[1] = *Vec2;
7842 // Add this built-in operator as a candidate (VQ is empty).
7843 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smithe54c3072013-05-05 15:51:06 +00007844 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007845 /*IsAssigmentOperator=*/isEqualOp);
7846
7847 // Add this built-in operator as a candidate (VQ is 'volatile').
7848 if (VisibleTypeConversionsQuals.hasVolatile()) {
7849 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7850 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007851 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007852 /*IsAssigmentOperator=*/isEqualOp);
7853 }
7854 }
7855 }
7856 }
7857
7858 // C++ [over.built]p22:
7859 //
7860 // For every triple (L, VQ, R), where L is an integral type, VQ
7861 // is either volatile or empty, and R is a promoted integral
7862 // type, there exist candidate operator functions of the form
7863 //
7864 // VQ L& operator%=(VQ L&, R);
7865 // VQ L& operator<<=(VQ L&, R);
7866 // VQ L& operator>>=(VQ L&, R);
7867 // VQ L& operator&=(VQ L&, R);
7868 // VQ L& operator^=(VQ L&, R);
7869 // VQ L& operator|=(VQ L&, R);
7870 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007871 if (!HasArithmeticOrEnumeralCandidateType)
7872 return;
7873
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007874 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7875 for (unsigned Right = FirstPromotedIntegralType;
7876 Right < LastPromotedIntegralType; ++Right) {
7877 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007878 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007879
7880 // Add this built-in operator as a candidate (VQ is empty).
7881 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007882 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007883 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007884 if (VisibleTypeConversionsQuals.hasVolatile()) {
7885 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00007886 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007887 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7888 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007889 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007890 }
7891 }
7892 }
7893 }
7894
7895 // C++ [over.operator]p23:
7896 //
7897 // There also exist candidate operator functions of the form
7898 //
7899 // bool operator!(bool);
7900 // bool operator&&(bool, bool);
7901 // bool operator||(bool, bool);
7902 void addExclaimOverload() {
7903 QualType ParamTy = S.Context.BoolTy;
Richard Smithe54c3072013-05-05 15:51:06 +00007904 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007905 /*IsAssignmentOperator=*/false,
7906 /*NumContextualBoolArguments=*/1);
7907 }
7908 void addAmpAmpOrPipePipeOverload() {
7909 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007910 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007911 /*IsAssignmentOperator=*/false,
7912 /*NumContextualBoolArguments=*/2);
7913 }
7914
7915 // C++ [over.built]p13:
7916 //
7917 // For every cv-qualified or cv-unqualified object type T there
7918 // exist candidate operator functions of the form
7919 //
7920 // T* operator+(T*, ptrdiff_t); [ABOVE]
7921 // T& operator[](T*, ptrdiff_t);
7922 // T* operator-(T*, ptrdiff_t); [ABOVE]
7923 // T* operator+(ptrdiff_t, T*); [ABOVE]
7924 // T& operator[](ptrdiff_t, T*);
7925 void addSubscriptOverloads() {
7926 for (BuiltinCandidateTypeSet::iterator
7927 Ptr = CandidateTypes[0].pointer_begin(),
7928 PtrEnd = CandidateTypes[0].pointer_end();
7929 Ptr != PtrEnd; ++Ptr) {
7930 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7931 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007932 if (!PointeeType->isObjectType())
7933 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007934
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007935 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7936
7937 // T& operator[](T*, ptrdiff_t)
Richard Smithe54c3072013-05-05 15:51:06 +00007938 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007939 }
7940
7941 for (BuiltinCandidateTypeSet::iterator
7942 Ptr = CandidateTypes[1].pointer_begin(),
7943 PtrEnd = CandidateTypes[1].pointer_end();
7944 Ptr != PtrEnd; ++Ptr) {
7945 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7946 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007947 if (!PointeeType->isObjectType())
7948 continue;
7949
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007950 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7951
7952 // T& operator[](ptrdiff_t, T*)
Richard Smithe54c3072013-05-05 15:51:06 +00007953 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007954 }
7955 }
7956
7957 // C++ [over.built]p11:
7958 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7959 // C1 is the same type as C2 or is a derived class of C2, T is an object
7960 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7961 // there exist candidate operator functions of the form
7962 //
7963 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7964 //
7965 // where CV12 is the union of CV1 and CV2.
7966 void addArrowStarOverloads() {
7967 for (BuiltinCandidateTypeSet::iterator
7968 Ptr = CandidateTypes[0].pointer_begin(),
7969 PtrEnd = CandidateTypes[0].pointer_end();
7970 Ptr != PtrEnd; ++Ptr) {
7971 QualType C1Ty = (*Ptr);
7972 QualType C1;
7973 QualifierCollector Q1;
7974 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7975 if (!isa<RecordType>(C1))
7976 continue;
7977 // heuristic to reduce number of builtin candidates in the set.
7978 // Add volatile/restrict version only if there are conversions to a
7979 // volatile/restrict type.
7980 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7981 continue;
7982 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7983 continue;
7984 for (BuiltinCandidateTypeSet::iterator
7985 MemPtr = CandidateTypes[1].member_pointer_begin(),
7986 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7987 MemPtr != MemPtrEnd; ++MemPtr) {
7988 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7989 QualType C2 = QualType(mptr->getClass(), 0);
7990 C2 = C2.getUnqualifiedType();
7991 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7992 break;
7993 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7994 // build CV12 T&
7995 QualType T = mptr->getPointeeType();
7996 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7997 T.isVolatileQualified())
7998 continue;
7999 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8000 T.isRestrictQualified())
8001 continue;
8002 T = Q1.apply(S.Context, T);
8003 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smithe54c3072013-05-05 15:51:06 +00008004 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008005 }
8006 }
8007 }
8008
8009 // Note that we don't consider the first argument, since it has been
8010 // contextually converted to bool long ago. The candidates below are
8011 // therefore added as binary.
8012 //
8013 // C++ [over.built]p25:
8014 // For every type T, where T is a pointer, pointer-to-member, or scoped
8015 // enumeration type, there exist candidate operator functions of the form
8016 //
8017 // T operator?(bool, T, T);
8018 //
8019 void addConditionalOperatorOverloads() {
8020 /// Set of (canonical) types that we've already handled.
8021 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8022
8023 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8024 for (BuiltinCandidateTypeSet::iterator
8025 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8026 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8027 Ptr != PtrEnd; ++Ptr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008028 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008029 continue;
8030
8031 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00008032 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008033 }
8034
8035 for (BuiltinCandidateTypeSet::iterator
8036 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8037 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8038 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008039 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008040 continue;
8041
8042 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00008043 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008044 }
8045
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008046 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008047 for (BuiltinCandidateTypeSet::iterator
8048 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8049 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8050 Enum != EnumEnd; ++Enum) {
8051 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8052 continue;
8053
David Blaikie82e95a32014-11-19 07:49:47 +00008054 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008055 continue;
8056
8057 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00008058 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008059 }
8060 }
8061 }
8062 }
8063};
8064
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008065} // end anonymous namespace
8066
8067/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8068/// operator overloads to the candidate set (C++ [over.built]), based
8069/// on the operator @p Op and the arguments given. For example, if the
8070/// operator is a binary '+', this routine might add "int
8071/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00008072void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8073 SourceLocation OpLoc,
8074 ArrayRef<Expr *> Args,
8075 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00008076 // Find all of the types that the arguments can convert to, but only
8077 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00008078 // that make use of these types. Also record whether we encounter non-record
8079 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00008080 Qualifiers VisibleTypeConversionsQuals;
8081 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00008082 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00008083 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00008084
8085 bool HasNonRecordCandidateType = false;
8086 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008087 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00008088 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008089 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
8090 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8091 OpLoc,
8092 true,
8093 (Op == OO_Exclaim ||
8094 Op == OO_AmpAmp ||
8095 Op == OO_PipePipe),
8096 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00008097 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8098 CandidateTypes[ArgIdx].hasNonRecordTypes();
8099 HasArithmeticOrEnumeralCandidateType =
8100 HasArithmeticOrEnumeralCandidateType ||
8101 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008102 }
Douglas Gregora11693b2008-11-12 17:17:38 +00008103
Chandler Carruth00a38332010-12-13 01:44:01 +00008104 // Exit early when no non-record types have been added to the candidate set
8105 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008106 //
8107 // We can't exit early for !, ||, or &&, since there we have always have
8108 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008109 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008110 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00008111 return;
8112
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008113 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008114 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008115 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00008116 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008117 CandidateTypes, CandidateSet);
8118
8119 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00008120 switch (Op) {
8121 case OO_None:
8122 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00008123 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00008124
Chandler Carruth5184de02010-12-12 08:51:33 +00008125 case OO_New:
8126 case OO_Delete:
8127 case OO_Array_New:
8128 case OO_Array_Delete:
8129 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00008130 llvm_unreachable(
8131 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00008132
8133 case OO_Comma:
8134 case OO_Arrow:
8135 // C++ [over.match.oper]p3:
8136 // -- For the operator ',', the unary operator '&', or the
8137 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00008138 break;
8139
8140 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008141 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008142 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00008143 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00008144
8145 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008146 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008147 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008148 } else {
8149 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8150 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8151 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008152 break;
8153
Chandler Carruth5184de02010-12-12 08:51:33 +00008154 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008155 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008156 OpBuilder.addUnaryStarPointerOverloads();
8157 else
8158 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8159 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008160
Chandler Carruth5184de02010-12-12 08:51:33 +00008161 case OO_Slash:
8162 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008163 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008164
8165 case OO_PlusPlus:
8166 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008167 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8168 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008169 break;
8170
Douglas Gregor84605ae2009-08-24 13:43:27 +00008171 case OO_EqualEqual:
8172 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008173 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008174 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008175
Douglas Gregora11693b2008-11-12 17:17:38 +00008176 case OO_Less:
8177 case OO_Greater:
8178 case OO_LessEqual:
8179 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008180 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008181 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8182 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008183
Douglas Gregora11693b2008-11-12 17:17:38 +00008184 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008185 case OO_Caret:
8186 case OO_Pipe:
8187 case OO_LessLess:
8188 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008189 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008190 break;
8191
Chandler Carruth5184de02010-12-12 08:51:33 +00008192 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008193 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008194 // C++ [over.match.oper]p3:
8195 // -- For the operator ',', the unary operator '&', or the
8196 // operator '->', the built-in candidates set is empty.
8197 break;
8198
8199 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8200 break;
8201
8202 case OO_Tilde:
8203 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8204 break;
8205
Douglas Gregora11693b2008-11-12 17:17:38 +00008206 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008207 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008208 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008209
8210 case OO_PlusEqual:
8211 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008212 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008213 // Fall through.
8214
8215 case OO_StarEqual:
8216 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008217 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008218 break;
8219
8220 case OO_PercentEqual:
8221 case OO_LessLessEqual:
8222 case OO_GreaterGreaterEqual:
8223 case OO_AmpEqual:
8224 case OO_CaretEqual:
8225 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008226 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008227 break;
8228
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008229 case OO_Exclaim:
8230 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008231 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008232
Douglas Gregora11693b2008-11-12 17:17:38 +00008233 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008234 case OO_PipePipe:
8235 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008236 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008237
8238 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008239 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008240 break;
8241
8242 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008243 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008244 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008245
8246 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008247 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008248 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8249 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008250 }
8251}
8252
Douglas Gregore254f902009-02-04 00:32:51 +00008253/// \brief Add function candidates found via argument-dependent lookup
8254/// to the set of overloading candidates.
8255///
8256/// This routine performs argument-dependent name lookup based on the
8257/// given function name (which may also be an operator name) and adds
8258/// all of the overload candidates found by ADL to the overload
8259/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008260void
Douglas Gregore254f902009-02-04 00:32:51 +00008261Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smith100b24a2014-04-17 01:52:14 +00008262 SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008263 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008264 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008265 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008266 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008267 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008268
John McCall91f61fc2010-01-26 06:04:06 +00008269 // FIXME: This approach for uniquing ADL results (and removing
8270 // redundant candidates from the set) relies on pointer-equality,
8271 // which means we need to key off the canonical decl. However,
8272 // always going back to the canonical decl might not get us the
8273 // right set of default arguments. What default arguments are
8274 // we supposed to consider on ADL candidates, anyway?
8275
Douglas Gregorcabea402009-09-22 15:41:20 +00008276 // FIXME: Pass in the explicit template arguments?
Richard Smith100b24a2014-04-17 01:52:14 +00008277 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008278
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008279 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008280 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8281 CandEnd = CandidateSet.end();
8282 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008283 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008284 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008285 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008286 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008287 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008288
8289 // For each of the ADL candidates we found, add it to the overload
8290 // set.
John McCall8fe68082010-01-26 07:16:45 +00008291 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008292 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008293 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008294 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008295 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008296
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008297 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8298 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008299 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008300 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008301 FoundDecl, ExplicitTemplateArgs,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00008302 Args, CandidateSet, PartialOverloading);
Douglas Gregor15448f82009-06-27 21:05:07 +00008303 }
Douglas Gregore254f902009-02-04 00:32:51 +00008304}
8305
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008306/// isBetterOverloadCandidate - Determines whether the first overload
8307/// candidate is a better candidate than the second (C++ 13.3.3p1).
Richard Smith17c00b42014-11-12 01:24:00 +00008308bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8309 const OverloadCandidate &Cand2,
8310 SourceLocation Loc,
8311 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008312 // Define viable functions to be better candidates than non-viable
8313 // functions.
8314 if (!Cand2.Viable)
8315 return Cand1.Viable;
8316 else if (!Cand1.Viable)
8317 return false;
8318
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008319 // C++ [over.match.best]p1:
8320 //
8321 // -- if F is a static member function, ICS1(F) is defined such
8322 // that ICS1(F) is neither better nor worse than ICS1(G) for
8323 // any function G, and, symmetrically, ICS1(G) is neither
8324 // better nor worse than ICS1(F).
8325 unsigned StartArg = 0;
8326 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8327 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008328
Douglas Gregord3cb3562009-07-07 23:38:56 +00008329 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008330 // A viable function F1 is defined to be a better function than another
8331 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008332 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00008333 unsigned NumArgs = Cand1.NumConversions;
8334 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008335 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008336 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00008337 switch (CompareImplicitConversionSequences(S,
8338 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008339 Cand2.Conversions[ArgIdx])) {
8340 case ImplicitConversionSequence::Better:
8341 // Cand1 has a better conversion sequence.
8342 HasBetterConversion = true;
8343 break;
8344
8345 case ImplicitConversionSequence::Worse:
8346 // Cand1 can't be better than Cand2.
8347 return false;
8348
8349 case ImplicitConversionSequence::Indistinguishable:
8350 // Do nothing.
8351 break;
8352 }
8353 }
8354
Mike Stump11289f42009-09-09 15:08:12 +00008355 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008356 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008357 if (HasBetterConversion)
8358 return true;
8359
Douglas Gregora1f013e2008-11-07 22:36:19 +00008360 // -- the context is an initialization by user-defined conversion
8361 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8362 // from the return type of F1 to the destination type (i.e.,
8363 // the type of the entity being initialized) is a better
8364 // conversion sequence than the standard conversion sequence
8365 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00008366 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00008367 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00008368 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00008369 // First check whether we prefer one of the conversion functions over the
8370 // other. This only distinguishes the results in non-standard, extension
8371 // cases such as the conversion from a lambda closure type to a function
8372 // pointer or block.
Richard Smithec2748a2014-05-17 04:36:39 +00008373 ImplicitConversionSequence::CompareKind Result =
8374 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8375 if (Result == ImplicitConversionSequence::Indistinguishable)
8376 Result = CompareStandardConversionSequences(S,
8377 Cand1.FinalConversion,
8378 Cand2.FinalConversion);
Richard Smith6fdeaab2014-05-17 01:58:45 +00008379
Richard Smithec2748a2014-05-17 04:36:39 +00008380 if (Result != ImplicitConversionSequence::Indistinguishable)
8381 return Result == ImplicitConversionSequence::Better;
Richard Smith6fdeaab2014-05-17 01:58:45 +00008382
8383 // FIXME: Compare kind of reference binding if conversion functions
8384 // convert to a reference type used in direct reference binding, per
8385 // C++14 [over.match.best]p1 section 2 bullet 3.
8386 }
8387
8388 // -- F1 is a non-template function and F2 is a function template
8389 // specialization, or, if not that,
8390 bool Cand1IsSpecialization = Cand1.Function &&
8391 Cand1.Function->getPrimaryTemplate();
8392 bool Cand2IsSpecialization = Cand2.Function &&
8393 Cand2.Function->getPrimaryTemplate();
8394 if (Cand1IsSpecialization != Cand2IsSpecialization)
8395 return Cand2IsSpecialization;
8396
8397 // -- F1 and F2 are function template specializations, and the function
8398 // template for F1 is more specialized than the template for F2
8399 // according to the partial ordering rules described in 14.5.5.2, or,
8400 // if not that,
8401 if (Cand1IsSpecialization && Cand2IsSpecialization) {
8402 if (FunctionTemplateDecl *BetterTemplate
8403 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8404 Cand2.Function->getPrimaryTemplate(),
8405 Loc,
8406 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8407 : TPOC_Call,
8408 Cand1.ExplicitCallArguments,
8409 Cand2.ExplicitCallArguments))
8410 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregora1f013e2008-11-07 22:36:19 +00008411 }
8412
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008413 // Check for enable_if value-based overload resolution.
8414 if (Cand1.Function && Cand2.Function &&
8415 (Cand1.Function->hasAttr<EnableIfAttr>() ||
8416 Cand2.Function->hasAttr<EnableIfAttr>())) {
8417 // FIXME: The next several lines are just
8418 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8419 // instead of reverse order which is how they're stored in the AST.
8420 AttrVec Cand1Attrs;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008421 if (Cand1.Function->hasAttrs()) {
8422 Cand1Attrs = Cand1.Function->getAttrs();
Richard Smith9516eee2014-05-17 02:21:47 +00008423 Cand1Attrs.erase(std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(),
8424 IsNotEnableIfAttr),
8425 Cand1Attrs.end());
8426 std::reverse(Cand1Attrs.begin(), Cand1Attrs.end());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008427 }
8428
8429 AttrVec Cand2Attrs;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008430 if (Cand2.Function->hasAttrs()) {
8431 Cand2Attrs = Cand2.Function->getAttrs();
Richard Smith9516eee2014-05-17 02:21:47 +00008432 Cand2Attrs.erase(std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(),
8433 IsNotEnableIfAttr),
8434 Cand2Attrs.end());
8435 std::reverse(Cand2Attrs.begin(), Cand2Attrs.end());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008436 }
Richard Smith9516eee2014-05-17 02:21:47 +00008437
8438 // Candidate 1 is better if it has strictly more attributes and
8439 // the common sequence is identical.
8440 if (Cand1Attrs.size() <= Cand2Attrs.size())
8441 return false;
8442
8443 auto Cand1I = Cand1Attrs.begin();
8444 for (auto &Cand2A : Cand2Attrs) {
8445 auto &Cand1A = *Cand1I++;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008446 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
Richard Smith9516eee2014-05-17 02:21:47 +00008447 cast<EnableIfAttr>(Cand1A)->getCond()->Profile(Cand1ID,
8448 S.getASTContext(), true);
8449 cast<EnableIfAttr>(Cand2A)->getCond()->Profile(Cand2ID,
8450 S.getASTContext(), true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00008451 if (Cand1ID != Cand2ID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008452 return false;
8453 }
Richard Smith9516eee2014-05-17 02:21:47 +00008454
8455 return true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008456 }
8457
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008458 return false;
8459}
8460
Mike Stump11289f42009-09-09 15:08:12 +00008461/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008462/// within an overload candidate set.
8463///
James Dennettffad8b72012-06-22 08:10:18 +00008464/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008465/// which overload resolution occurs.
8466///
James Dennettffad8b72012-06-22 08:10:18 +00008467/// \param Best If overload resolution was successful or found a deleted
8468/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008469///
8470/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00008471OverloadingResult
8472OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008473 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00008474 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008475 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00008476 Best = end();
8477 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8478 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008479 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008480 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008481 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008482 }
8483
8484 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00008485 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008486 return OR_No_Viable_Function;
8487
8488 // Make sure that this function is better than every other viable
8489 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00008490 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00008491 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008492 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008493 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008494 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00008495 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008496 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00008497 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008498 }
Mike Stump11289f42009-09-09 15:08:12 +00008499
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008500 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00008501 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008502 (Best->Function->isDeleted() ||
8503 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00008504 return OR_Deleted;
8505
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008506 return OR_Success;
8507}
8508
John McCall53262c92010-01-12 02:15:36 +00008509namespace {
8510
8511enum OverloadCandidateKind {
8512 oc_function,
8513 oc_method,
8514 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00008515 oc_function_template,
8516 oc_method_template,
8517 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00008518 oc_implicit_default_constructor,
8519 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008520 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00008521 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008522 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00008523 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00008524};
8525
John McCalle1ac8d12010-01-13 00:25:19 +00008526OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8527 FunctionDecl *Fn,
8528 std::string &Description) {
8529 bool isTemplate = false;
8530
8531 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8532 isTemplate = true;
8533 Description = S.getTemplateArgumentBindingsText(
8534 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8535 }
John McCallfd0b2f82010-01-06 09:43:14 +00008536
8537 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00008538 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008539 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008540
Sebastian Redl08905022011-02-05 19:23:19 +00008541 if (Ctor->getInheritedConstructor())
8542 return oc_implicit_inherited_constructor;
8543
Alexis Hunt119c10e2011-05-25 23:16:36 +00008544 if (Ctor->isDefaultConstructor())
8545 return oc_implicit_default_constructor;
8546
8547 if (Ctor->isMoveConstructor())
8548 return oc_implicit_move_constructor;
8549
8550 assert(Ctor->isCopyConstructor() &&
8551 "unexpected sort of implicit constructor");
8552 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008553 }
8554
8555 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8556 // This actually gets spelled 'candidate function' for now, but
8557 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00008558 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008559 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00008560
Alexis Hunt119c10e2011-05-25 23:16:36 +00008561 if (Meth->isMoveAssignmentOperator())
8562 return oc_implicit_move_assignment;
8563
Douglas Gregor12695102012-02-10 08:36:38 +00008564 if (Meth->isCopyAssignmentOperator())
8565 return oc_implicit_copy_assignment;
8566
8567 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8568 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00008569 }
8570
John McCalle1ac8d12010-01-13 00:25:19 +00008571 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00008572}
8573
Larisse Voufo98b20f12013-07-19 23:00:19 +00008574void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
Sebastian Redl08905022011-02-05 19:23:19 +00008575 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8576 if (!Ctor) return;
8577
8578 Ctor = Ctor->getInheritedConstructor();
8579 if (!Ctor) return;
8580
8581 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8582}
8583
John McCall53262c92010-01-12 02:15:36 +00008584} // end anonymous namespace
8585
8586// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00008587void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00008588 std::string FnDesc;
8589 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00008590 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8591 << (unsigned) K << FnDesc;
8592 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8593 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00008594 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00008595}
8596
Nick Lewyckyed4265c2013-09-22 10:06:01 +00008597// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00008598// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00008599void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008600 assert(OverloadedExpr->getType() == Context.OverloadTy);
8601
8602 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8603 OverloadExpr *OvlExpr = Ovl.Expression;
8604
8605 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8606 IEnd = OvlExpr->decls_end();
8607 I != IEnd; ++I) {
8608 if (FunctionTemplateDecl *FunTmpl =
8609 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00008610 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008611 } else if (FunctionDecl *Fun
8612 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00008613 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008614 }
8615 }
8616}
8617
John McCall0d1da222010-01-12 00:44:57 +00008618/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8619/// "lead" diagnostic; it will be given two arguments, the source and
8620/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00008621void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8622 Sema &S,
8623 SourceLocation CaretLoc,
8624 const PartialDiagnostic &PDiag) const {
8625 S.Diag(CaretLoc, PDiag)
8626 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008627 // FIXME: The note limiting machinery is borrowed from
8628 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8629 // refactoring here.
8630 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8631 unsigned CandsShown = 0;
8632 AmbiguousConversionSequence::const_iterator I, E;
8633 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8634 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8635 break;
8636 ++CandsShown;
John McCall5c32be02010-08-24 20:38:10 +00008637 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00008638 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008639 if (I != E)
8640 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00008641}
8642
Richard Smith17c00b42014-11-12 01:24:00 +00008643static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
8644 unsigned I) {
John McCall6a61b522010-01-13 09:16:55 +00008645 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8646 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00008647 assert(Cand->Function && "for now, candidate must be a function");
8648 FunctionDecl *Fn = Cand->Function;
8649
8650 // There's a conversion slot for the object argument if this is a
8651 // non-constructor method. Note that 'I' corresponds the
8652 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00008653 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00008654 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00008655 if (I == 0)
8656 isObjectArgument = true;
8657 else
8658 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00008659 }
8660
John McCalle1ac8d12010-01-13 00:25:19 +00008661 std::string FnDesc;
8662 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8663
John McCall6a61b522010-01-13 09:16:55 +00008664 Expr *FromExpr = Conv.Bad.FromExpr;
8665 QualType FromTy = Conv.Bad.getFromType();
8666 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00008667
John McCallfb7ad0f2010-02-02 02:42:52 +00008668 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00008669 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00008670 Expr *E = FromExpr->IgnoreParens();
8671 if (isa<UnaryOperator>(E))
8672 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00008673 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00008674
8675 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8676 << (unsigned) FnKind << FnDesc
8677 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8678 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008679 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00008680 return;
8681 }
8682
John McCall6d174642010-01-23 08:10:49 +00008683 // Do some hand-waving analysis to see if the non-viability is due
8684 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00008685 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8686 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8687 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8688 CToTy = RT->getPointeeType();
8689 else {
8690 // TODO: detect and diagnose the full richness of const mismatches.
8691 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8692 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8693 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8694 }
8695
8696 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8697 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00008698 Qualifiers FromQs = CFromTy.getQualifiers();
8699 Qualifiers ToQs = CToTy.getQualifiers();
8700
8701 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8702 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8703 << (unsigned) FnKind << FnDesc
8704 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8705 << FromTy
8706 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8707 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008708 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008709 return;
8710 }
8711
John McCall31168b02011-06-15 23:02:42 +00008712 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008713 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00008714 << (unsigned) FnKind << FnDesc
8715 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8716 << FromTy
8717 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8718 << (unsigned) isObjectArgument << I+1;
8719 MaybeEmitInheritedConstructorNote(S, Fn);
8720 return;
8721 }
8722
Douglas Gregoraec25842011-04-26 23:16:46 +00008723 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8724 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8725 << (unsigned) FnKind << FnDesc
8726 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8727 << FromTy
8728 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8729 << (unsigned) isObjectArgument << I+1;
8730 MaybeEmitInheritedConstructorNote(S, Fn);
8731 return;
8732 }
8733
John McCall47000992010-01-14 03:28:57 +00008734 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8735 assert(CVR && "unexpected qualifiers mismatch");
8736
8737 if (isObjectArgument) {
8738 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8739 << (unsigned) FnKind << FnDesc
8740 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8741 << FromTy << (CVR - 1);
8742 } else {
8743 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8744 << (unsigned) FnKind << FnDesc
8745 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8746 << FromTy << (CVR - 1) << I+1;
8747 }
Sebastian Redl08905022011-02-05 19:23:19 +00008748 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008749 return;
8750 }
8751
Sebastian Redla72462c2011-09-24 17:48:32 +00008752 // Special diagnostic for failure to convert an initializer list, since
8753 // telling the user that it has type void is not useful.
8754 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8755 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8756 << (unsigned) FnKind << FnDesc
8757 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8758 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8759 MaybeEmitInheritedConstructorNote(S, Fn);
8760 return;
8761 }
8762
John McCall6d174642010-01-23 08:10:49 +00008763 // Diagnose references or pointers to incomplete types differently,
8764 // since it's far from impossible that the incompleteness triggered
8765 // the failure.
8766 QualType TempFromTy = FromTy.getNonReferenceType();
8767 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8768 TempFromTy = PTy->getPointeeType();
8769 if (TempFromTy->isIncompleteType()) {
8770 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8771 << (unsigned) FnKind << FnDesc
8772 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8773 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008774 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00008775 return;
8776 }
8777
Douglas Gregor56f2e342010-06-30 23:01:39 +00008778 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008779 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008780 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8781 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8782 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8783 FromPtrTy->getPointeeType()) &&
8784 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8785 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008786 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00008787 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008788 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008789 }
8790 } else if (const ObjCObjectPointerType *FromPtrTy
8791 = FromTy->getAs<ObjCObjectPointerType>()) {
8792 if (const ObjCObjectPointerType *ToPtrTy
8793 = ToTy->getAs<ObjCObjectPointerType>())
8794 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8795 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8796 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8797 FromPtrTy->getPointeeType()) &&
8798 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008799 BaseToDerivedConversion = 2;
8800 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008801 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8802 !FromTy->isIncompleteType() &&
8803 !ToRefTy->getPointeeType()->isIncompleteType() &&
8804 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8805 BaseToDerivedConversion = 3;
8806 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8807 ToTy.getNonReferenceType().getCanonicalType() ==
8808 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008809 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8810 << (unsigned) FnKind << FnDesc
8811 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8812 << (unsigned) isObjectArgument << I + 1;
8813 MaybeEmitInheritedConstructorNote(S, Fn);
8814 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008815 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008816 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008817
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008818 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008819 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008820 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00008821 << (unsigned) FnKind << FnDesc
8822 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008823 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008824 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008825 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00008826 return;
8827 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008828
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00008829 if (isa<ObjCObjectPointerType>(CFromTy) &&
8830 isa<PointerType>(CToTy)) {
8831 Qualifiers FromQs = CFromTy.getQualifiers();
8832 Qualifiers ToQs = CToTy.getQualifiers();
8833 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8834 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8835 << (unsigned) FnKind << FnDesc
8836 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8837 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8838 MaybeEmitInheritedConstructorNote(S, Fn);
8839 return;
8840 }
8841 }
8842
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008843 // Emit the generic diagnostic and, optionally, add the hints to it.
8844 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8845 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00008846 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008847 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8848 << (unsigned) (Cand->Fix.Kind);
8849
8850 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00008851 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8852 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008853 FDiag << *HI;
8854 S.Diag(Fn->getLocation(), FDiag);
8855
Sebastian Redl08905022011-02-05 19:23:19 +00008856 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00008857}
8858
Larisse Voufo98b20f12013-07-19 23:00:19 +00008859/// Additional arity mismatch diagnosis specific to a function overload
8860/// candidates. This is not covered by the more general DiagnoseArityMismatch()
8861/// over a candidate in any candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00008862static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8863 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00008864 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00008865 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008866
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008867 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00008868 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008869 // right number of arguments, because only overloaded operators have
8870 // the weird behavior of overloading member and non-member functions.
8871 // Just don't report anything.
8872 if (Fn->isInvalidDecl() &&
8873 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008874 return true;
8875
8876 if (NumArgs < MinParams) {
8877 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8878 (Cand->FailureKind == ovl_fail_bad_deduction &&
8879 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8880 } else {
8881 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8882 (Cand->FailureKind == ovl_fail_bad_deduction &&
8883 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8884 }
8885
8886 return false;
8887}
8888
8889/// General arity mismatch diagnosis over a candidate in a candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00008890static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008891 assert(isa<FunctionDecl>(D) &&
8892 "The templated declaration should at least be a function"
8893 " when diagnosing bad template argument deduction due to too many"
8894 " or too few arguments");
8895
8896 FunctionDecl *Fn = cast<FunctionDecl>(D);
8897
8898 // TODO: treat calls to a missing default constructor as a special case
8899 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8900 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008901
John McCall6a61b522010-01-13 09:16:55 +00008902 // at least / at most / exactly
8903 unsigned mode, modeCount;
8904 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00008905 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
8906 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00008907 mode = 0; // "at least"
8908 else
8909 mode = 2; // "exactly"
8910 modeCount = MinParams;
8911 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00008912 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00008913 mode = 1; // "at most"
8914 else
8915 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00008916 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00008917 }
8918
8919 std::string Description;
8920 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8921
Richard Smith10ff50d2012-05-11 05:16:41 +00008922 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8923 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Craig Topperc3ec1492014-05-26 06:22:03 +00008924 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8925 << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smith10ff50d2012-05-11 05:16:41 +00008926 else
8927 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Craig Topperc3ec1492014-05-26 06:22:03 +00008928 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8929 << mode << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00008930 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008931}
8932
Larisse Voufo98b20f12013-07-19 23:00:19 +00008933/// Arity mismatch diagnosis specific to a function overload candidate.
Richard Smith17c00b42014-11-12 01:24:00 +00008934static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8935 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008936 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
8937 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
8938}
Larisse Voufo47c08452013-07-19 22:53:23 +00008939
Richard Smith17c00b42014-11-12 01:24:00 +00008940static TemplateDecl *getDescribedTemplate(Decl *Templated) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008941 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
8942 return FD->getDescribedFunctionTemplate();
8943 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
8944 return RD->getDescribedClassTemplate();
8945
8946 llvm_unreachable("Unsupported: Getting the described template declaration"
8947 " for bad deduction diagnosis");
8948}
8949
8950/// Diagnose a failed template-argument deduction.
Richard Smith17c00b42014-11-12 01:24:00 +00008951static void DiagnoseBadDeduction(Sema &S, Decl *Templated,
8952 DeductionFailureInfo &DeductionFailure,
8953 unsigned NumArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008954 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008955 NamedDecl *ParamD;
8956 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8957 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8958 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00008959 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00008960 case Sema::TDK_Success:
8961 llvm_unreachable("TDK_success while diagnosing bad deduction");
8962
8963 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00008964 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00008965 S.Diag(Templated->getLocation(),
8966 diag::note_ovl_candidate_incomplete_deduction)
8967 << ParamD->getDeclName();
8968 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00008969 return;
8970 }
8971
John McCall42d7d192010-08-05 09:05:08 +00008972 case Sema::TDK_Underqualified: {
8973 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8974 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8975
Larisse Voufo98b20f12013-07-19 23:00:19 +00008976 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00008977
8978 // Param will have been canonicalized, but it should just be a
8979 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00008980 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00008981 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00008982 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00008983 assert(S.Context.hasSameType(Param, NonCanonParam));
8984
8985 // Arg has also been canonicalized, but there's nothing we can do
8986 // about that. It also doesn't matter as much, because it won't
8987 // have any template parameters in it (because deduction isn't
8988 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00008989 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00008990
Larisse Voufo98b20f12013-07-19 23:00:19 +00008991 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
8992 << ParamD->getDeclName() << Arg << NonCanonParam;
8993 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall42d7d192010-08-05 09:05:08 +00008994 return;
8995 }
8996
8997 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00008998 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008999 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009000 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009001 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009002 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009003 which = 1;
9004 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009005 which = 2;
9006 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009007
Larisse Voufo98b20f12013-07-19 23:00:19 +00009008 S.Diag(Templated->getLocation(),
9009 diag::note_ovl_candidate_inconsistent_deduction)
9010 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9011 << *DeductionFailure.getSecondArg();
9012 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009013 return;
9014 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00009015
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009016 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009017 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009018 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00009019 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009020 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009021 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009022 else {
9023 int index = 0;
9024 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9025 index = TTP->getIndex();
9026 else if (NonTypeTemplateParmDecl *NTTP
9027 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9028 index = NTTP->getIndex();
9029 else
9030 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00009031 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009032 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009033 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009034 }
Larisse Voufo98b20f12013-07-19 23:00:19 +00009035 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009036 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009037
Douglas Gregor02eb4832010-05-08 18:13:28 +00009038 case Sema::TDK_TooManyArguments:
9039 case Sema::TDK_TooFewArguments:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009040 DiagnoseArityMismatch(S, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00009041 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00009042
9043 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009044 S.Diag(Templated->getLocation(),
9045 diag::note_ovl_candidate_instantiation_depth);
9046 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00009047 return;
9048
9049 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00009050 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009051 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009052 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00009053 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00009054 TemplateArgString = " ";
9055 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00009056 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00009057 }
9058
Richard Smith6f8d2c62012-05-09 05:17:00 +00009059 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009060 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009061 if (PDiag && PDiag->second.getDiagID() ==
9062 diag::err_typename_nested_not_found_enable_if) {
9063 // FIXME: Use the source range of the condition, and the fully-qualified
9064 // name of the enable_if template. These are both present in PDiag.
9065 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9066 << "'enable_if'" << TemplateArgString;
9067 return;
9068 }
9069
Richard Smith9ca64612012-05-07 09:03:25 +00009070 // Format the SFINAE diagnostic into the argument string.
9071 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9072 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009073 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009074 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009075 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00009076 SFINAEArgString = ": ";
9077 R = SourceRange(PDiag->first, PDiag->first);
9078 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9079 }
9080
Larisse Voufo98b20f12013-07-19 23:00:19 +00009081 S.Diag(Templated->getLocation(),
9082 diag::note_ovl_candidate_substitution_failure)
9083 << TemplateArgString << SFINAEArgString << R;
9084 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00009085 return;
9086 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009087
Richard Smith8c6eeb92013-01-31 04:03:12 +00009088 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009089 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9090 S.Diag(Templated->getLocation(),
Richard Smith8c6eeb92013-01-31 04:03:12 +00009091 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009092 << R.Expression->getName();
Richard Smith8c6eeb92013-01-31 04:03:12 +00009093 return;
9094 }
9095
Richard Trieue3732352013-04-08 21:11:40 +00009096 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00009097 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009098 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9099 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00009100 if (FirstTA.getKind() == TemplateArgument::Template &&
9101 SecondTA.getKind() == TemplateArgument::Template) {
9102 TemplateName FirstTN = FirstTA.getAsTemplate();
9103 TemplateName SecondTN = SecondTA.getAsTemplate();
9104 if (FirstTN.getKind() == TemplateName::Template &&
9105 SecondTN.getKind() == TemplateName::Template) {
9106 if (FirstTN.getAsTemplateDecl()->getName() ==
9107 SecondTN.getAsTemplateDecl()->getName()) {
9108 // FIXME: This fixes a bad diagnostic where both templates are named
9109 // the same. This particular case is a bit difficult since:
9110 // 1) It is passed as a string to the diagnostic printer.
9111 // 2) The diagnostic printer only attempts to find a better
9112 // name for types, not decls.
9113 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009114 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +00009115 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9116 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9117 return;
9118 }
9119 }
9120 }
Faisal Vali2b391ab2013-09-26 19:54:12 +00009121 // FIXME: For generic lambda parameters, check if the function is a lambda
9122 // call operator, and if so, emit a prettier and more informative
9123 // diagnostic that mentions 'auto' and lambda in addition to
9124 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009125 S.Diag(Templated->getLocation(),
9126 diag::note_ovl_candidate_non_deduced_mismatch)
9127 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +00009128 return;
Richard Trieue3732352013-04-08 21:11:40 +00009129 }
John McCall8b9ed552010-02-01 18:53:26 +00009130 // TODO: diagnose these individually, then kill off
9131 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +00009132 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009133 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9134 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00009135 return;
9136 }
9137}
9138
Larisse Voufo98b20f12013-07-19 23:00:19 +00009139/// Diagnose a failed template-argument deduction, for function calls.
Richard Smith17c00b42014-11-12 01:24:00 +00009140static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
9141 unsigned NumArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009142 unsigned TDK = Cand->DeductionFailure.Result;
9143 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9144 if (CheckArityMismatch(S, Cand, NumArgs))
9145 return;
9146 }
9147 DiagnoseBadDeduction(S, Cand->Function, // pattern
9148 Cand->DeductionFailure, NumArgs);
9149}
9150
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009151/// CUDA: diagnose an invalid call across targets.
Richard Smith17c00b42014-11-12 01:24:00 +00009152static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009153 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9154 FunctionDecl *Callee = Cand->Function;
9155
9156 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9157 CalleeTarget = S.IdentifyCUDATarget(Callee);
9158
9159 std::string FnDesc;
9160 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
9161
9162 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009163 << (unsigned)FnKind << CalleeTarget << CallerTarget;
9164
9165 // This could be an implicit constructor for which we could not infer the
9166 // target due to a collsion. Diagnose that case.
9167 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9168 if (Meth != nullptr && Meth->isImplicit()) {
9169 CXXRecordDecl *ParentClass = Meth->getParent();
9170 Sema::CXXSpecialMember CSM;
9171
9172 switch (FnKind) {
9173 default:
9174 return;
9175 case oc_implicit_default_constructor:
9176 CSM = Sema::CXXDefaultConstructor;
9177 break;
9178 case oc_implicit_copy_constructor:
9179 CSM = Sema::CXXCopyConstructor;
9180 break;
9181 case oc_implicit_move_constructor:
9182 CSM = Sema::CXXMoveConstructor;
9183 break;
9184 case oc_implicit_copy_assignment:
9185 CSM = Sema::CXXCopyAssignment;
9186 break;
9187 case oc_implicit_move_assignment:
9188 CSM = Sema::CXXMoveAssignment;
9189 break;
9190 };
9191
9192 bool ConstRHS = false;
9193 if (Meth->getNumParams()) {
9194 if (const ReferenceType *RT =
9195 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9196 ConstRHS = RT->getPointeeType().isConstQualified();
9197 }
9198 }
9199
9200 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9201 /* ConstRHS */ ConstRHS,
9202 /* Diagnose */ true);
9203 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009204}
9205
Richard Smith17c00b42014-11-12 01:24:00 +00009206static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009207 FunctionDecl *Callee = Cand->Function;
9208 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9209
9210 S.Diag(Callee->getLocation(),
9211 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9212 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9213}
9214
John McCall8b9ed552010-02-01 18:53:26 +00009215/// Generates a 'note' diagnostic for an overload candidate. We've
9216/// already generated a primary error at the call site.
9217///
9218/// It really does need to be a single diagnostic with its caret
9219/// pointed at the candidate declaration. Yes, this creates some
9220/// major challenges of technical writing. Yes, this makes pointing
9221/// out problems with specific arguments quite awkward. It's still
9222/// better than generating twenty screens of text for every failed
9223/// overload.
9224///
9225/// It would be great to be able to express per-candidate problems
9226/// more richly for those diagnostic clients that cared, but we'd
9227/// still have to be just as careful with the default diagnostics.
Richard Smith17c00b42014-11-12 01:24:00 +00009228static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
9229 unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00009230 FunctionDecl *Fn = Cand->Function;
9231
John McCall12f97bc2010-01-08 04:41:39 +00009232 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009233 if (Cand->Viable && (Fn->isDeleted() ||
9234 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00009235 std::string FnDesc;
9236 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00009237
9238 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00009239 << FnKind << FnDesc
9240 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redl08905022011-02-05 19:23:19 +00009241 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00009242 return;
John McCall12f97bc2010-01-08 04:41:39 +00009243 }
9244
John McCalle1ac8d12010-01-13 00:25:19 +00009245 // We don't really have anything else to say about viable candidates.
9246 if (Cand->Viable) {
9247 S.NoteOverloadCandidate(Fn);
9248 return;
9249 }
John McCall0d1da222010-01-12 00:44:57 +00009250
John McCall6a61b522010-01-13 09:16:55 +00009251 switch (Cand->FailureKind) {
9252 case ovl_fail_too_many_arguments:
9253 case ovl_fail_too_few_arguments:
9254 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00009255
John McCall6a61b522010-01-13 09:16:55 +00009256 case ovl_fail_bad_deduction:
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009257 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall8b9ed552010-02-01 18:53:26 +00009258
John McCall578a1f82014-12-14 01:46:53 +00009259 case ovl_fail_illegal_constructor: {
9260 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9261 << (Fn->getPrimaryTemplate() ? 1 : 0);
9262 MaybeEmitInheritedConstructorNote(S, Fn);
9263 return;
9264 }
9265
John McCallfe796dd2010-01-23 05:17:32 +00009266 case ovl_fail_trivial_conversion:
9267 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00009268 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00009269 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009270
John McCall65eb8792010-02-25 01:37:24 +00009271 case ovl_fail_bad_conversion: {
9272 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009273 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00009274 if (Cand->Conversions[I].isBad())
9275 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009276
John McCall6a61b522010-01-13 09:16:55 +00009277 // FIXME: this currently happens when we're called from SemaInit
9278 // when user-conversion overload fails. Figure out how to handle
9279 // those conditions and diagnose them well.
9280 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009281 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009282
9283 case ovl_fail_bad_target:
9284 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009285
9286 case ovl_fail_enable_if:
9287 return DiagnoseFailedEnableIfAttr(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00009288 }
John McCalld3224162010-01-08 00:58:21 +00009289}
9290
Richard Smith17c00b42014-11-12 01:24:00 +00009291static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
John McCalld3224162010-01-08 00:58:21 +00009292 // Desugar the type of the surrogate down to a function type,
9293 // retaining as many typedefs as possible while still showing
9294 // the function type (and, therefore, its parameter types).
9295 QualType FnType = Cand->Surrogate->getConversionType();
9296 bool isLValueReference = false;
9297 bool isRValueReference = false;
9298 bool isPointer = false;
9299 if (const LValueReferenceType *FnTypeRef =
9300 FnType->getAs<LValueReferenceType>()) {
9301 FnType = FnTypeRef->getPointeeType();
9302 isLValueReference = true;
9303 } else if (const RValueReferenceType *FnTypeRef =
9304 FnType->getAs<RValueReferenceType>()) {
9305 FnType = FnTypeRef->getPointeeType();
9306 isRValueReference = true;
9307 }
9308 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9309 FnType = FnTypePtr->getPointeeType();
9310 isPointer = true;
9311 }
9312 // Desugar down to a function type.
9313 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9314 // Reconstruct the pointer/reference as appropriate.
9315 if (isPointer) FnType = S.Context.getPointerType(FnType);
9316 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9317 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9318
9319 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9320 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00009321 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00009322}
9323
Richard Smith17c00b42014-11-12 01:24:00 +00009324static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9325 SourceLocation OpLoc,
9326 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009327 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00009328 std::string TypeStr("operator");
9329 TypeStr += Opc;
9330 TypeStr += "(";
9331 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00009332 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00009333 TypeStr += ")";
9334 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9335 } else {
9336 TypeStr += ", ";
9337 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9338 TypeStr += ")";
9339 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9340 }
9341}
9342
Richard Smith17c00b42014-11-12 01:24:00 +00009343static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9344 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009345 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00009346 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9347 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00009348 if (ICS.isBad()) break; // all meaningless after first invalid
9349 if (!ICS.isAmbiguous()) continue;
9350
John McCall5c32be02010-08-24 20:38:10 +00009351 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00009352 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00009353 }
9354}
9355
Larisse Voufo98b20f12013-07-19 23:00:19 +00009356static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +00009357 if (Cand->Function)
9358 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00009359 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00009360 return Cand->Surrogate->getLocation();
9361 return SourceLocation();
9362}
9363
Larisse Voufo98b20f12013-07-19 23:00:19 +00009364static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00009365 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009366 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00009367 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009368
Douglas Gregorc5c01a62012-09-13 21:01:57 +00009369 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009370 case Sema::TDK_Incomplete:
9371 return 1;
9372
9373 case Sema::TDK_Underqualified:
9374 case Sema::TDK_Inconsistent:
9375 return 2;
9376
9377 case Sema::TDK_SubstitutionFailure:
9378 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +00009379 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009380 return 3;
9381
9382 case Sema::TDK_InstantiationDepth:
9383 case Sema::TDK_FailedOverloadResolution:
9384 return 4;
9385
9386 case Sema::TDK_InvalidExplicitArguments:
9387 return 5;
9388
9389 case Sema::TDK_TooManyArguments:
9390 case Sema::TDK_TooFewArguments:
9391 return 6;
9392 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009393 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009394}
9395
Richard Smith17c00b42014-11-12 01:24:00 +00009396namespace {
John McCallad2587a2010-01-12 00:48:53 +00009397struct CompareOverloadCandidatesForDisplay {
9398 Sema &S;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009399 size_t NumArgs;
9400
9401 CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs)
9402 : S(S), NumArgs(nArgs) {}
John McCall12f97bc2010-01-08 04:41:39 +00009403
9404 bool operator()(const OverloadCandidate *L,
9405 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00009406 // Fast-path this check.
9407 if (L == R) return false;
9408
John McCall12f97bc2010-01-08 04:41:39 +00009409 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00009410 if (L->Viable) {
9411 if (!R->Viable) return true;
9412
9413 // TODO: introduce a tri-valued comparison for overload
9414 // candidates. Would be more worthwhile if we had a sort
9415 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00009416 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9417 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00009418 } else if (R->Viable)
9419 return false;
John McCall12f97bc2010-01-08 04:41:39 +00009420
John McCall3712d9e2010-01-15 23:32:50 +00009421 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00009422
John McCall3712d9e2010-01-15 23:32:50 +00009423 // Criteria by which we can sort non-viable candidates:
9424 if (!L->Viable) {
9425 // 1. Arity mismatches come after other candidates.
9426 if (L->FailureKind == ovl_fail_too_many_arguments ||
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009427 L->FailureKind == ovl_fail_too_few_arguments) {
9428 if (R->FailureKind == ovl_fail_too_many_arguments ||
9429 R->FailureKind == ovl_fail_too_few_arguments) {
Kaelyn Takata50c4ffc2014-05-07 00:43:38 +00009430 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9431 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9432 if (LDist == RDist) {
9433 if (L->FailureKind == R->FailureKind)
9434 // Sort non-surrogates before surrogates.
9435 return !L->IsSurrogate && R->IsSurrogate;
9436 // Sort candidates requiring fewer parameters than there were
9437 // arguments given after candidates requiring more parameters
9438 // than there were arguments given.
9439 return L->FailureKind == ovl_fail_too_many_arguments;
9440 }
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009441 return LDist < RDist;
9442 }
John McCall3712d9e2010-01-15 23:32:50 +00009443 return false;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009444 }
John McCall3712d9e2010-01-15 23:32:50 +00009445 if (R->FailureKind == ovl_fail_too_many_arguments ||
9446 R->FailureKind == ovl_fail_too_few_arguments)
9447 return true;
John McCall12f97bc2010-01-08 04:41:39 +00009448
John McCallfe796dd2010-01-23 05:17:32 +00009449 // 2. Bad conversions come first and are ordered by the number
9450 // of bad conversions and quality of good conversions.
9451 if (L->FailureKind == ovl_fail_bad_conversion) {
9452 if (R->FailureKind != ovl_fail_bad_conversion)
9453 return true;
9454
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009455 // The conversion that can be fixed with a smaller number of changes,
9456 // comes first.
9457 unsigned numLFixes = L->Fix.NumConversionsFixed;
9458 unsigned numRFixes = R->Fix.NumConversionsFixed;
9459 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9460 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009461 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009462 if (numLFixes < numRFixes)
9463 return true;
9464 else
9465 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009466 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009467
John McCallfe796dd2010-01-23 05:17:32 +00009468 // If there's any ordering between the defined conversions...
9469 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00009470 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00009471
9472 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00009473 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009474 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00009475 switch (CompareImplicitConversionSequences(S,
9476 L->Conversions[I],
9477 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00009478 case ImplicitConversionSequence::Better:
9479 leftBetter++;
9480 break;
9481
9482 case ImplicitConversionSequence::Worse:
9483 leftBetter--;
9484 break;
9485
9486 case ImplicitConversionSequence::Indistinguishable:
9487 break;
9488 }
9489 }
9490 if (leftBetter > 0) return true;
9491 if (leftBetter < 0) return false;
9492
9493 } else if (R->FailureKind == ovl_fail_bad_conversion)
9494 return false;
9495
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009496 if (L->FailureKind == ovl_fail_bad_deduction) {
9497 if (R->FailureKind != ovl_fail_bad_deduction)
9498 return true;
9499
9500 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9501 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00009502 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00009503 } else if (R->FailureKind == ovl_fail_bad_deduction)
9504 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009505
John McCall3712d9e2010-01-15 23:32:50 +00009506 // TODO: others?
9507 }
9508
9509 // Sort everything else by location.
9510 SourceLocation LLoc = GetLocationForCandidate(L);
9511 SourceLocation RLoc = GetLocationForCandidate(R);
9512
9513 // Put candidates without locations (e.g. builtins) at the end.
9514 if (LLoc.isInvalid()) return false;
9515 if (RLoc.isInvalid()) return true;
9516
9517 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00009518 }
9519};
Richard Smith17c00b42014-11-12 01:24:00 +00009520}
John McCall12f97bc2010-01-08 04:41:39 +00009521
John McCallfe796dd2010-01-23 05:17:32 +00009522/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009523/// computes up to the first. Produces the FixIt set if possible.
Richard Smith17c00b42014-11-12 01:24:00 +00009524static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9525 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00009526 assert(!Cand->Viable);
9527
9528 // Don't do anything on failures other than bad conversion.
9529 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9530
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009531 // We only want the FixIts if all the arguments can be corrected.
9532 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00009533 // Use a implicit copy initialization to check conversion fixes.
9534 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009535
John McCallfe796dd2010-01-23 05:17:32 +00009536 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00009537 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009538 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00009539 while (true) {
9540 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9541 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009542 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00009543 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00009544 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009545 }
John McCallfe796dd2010-01-23 05:17:32 +00009546 }
9547
9548 if (ConvIdx == ConvCount)
9549 return;
9550
John McCall65eb8792010-02-25 01:37:24 +00009551 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9552 "remaining conversion is initialized?");
9553
Douglas Gregoradc7a702010-04-16 17:45:54 +00009554 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00009555 // operation somehow.
9556 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00009557
9558 const FunctionProtoType* Proto;
9559 unsigned ArgIdx = ConvIdx;
9560
9561 if (Cand->IsSurrogate) {
9562 QualType ConvType
9563 = Cand->Surrogate->getConversionType().getNonReferenceType();
9564 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9565 ConvType = ConvPtrType->getPointeeType();
9566 Proto = ConvType->getAs<FunctionProtoType>();
9567 ArgIdx--;
9568 } else if (Cand->Function) {
9569 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9570 if (isa<CXXMethodDecl>(Cand->Function) &&
9571 !isa<CXXConstructorDecl>(Cand->Function))
9572 ArgIdx--;
9573 } else {
9574 // Builtin binary operator with a bad first conversion.
9575 assert(ConvCount <= 3);
9576 for (; ConvIdx != ConvCount; ++ConvIdx)
9577 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00009578 = TryCopyInitialization(S, Args[ConvIdx],
9579 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009580 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00009581 /*InOverloadResolution*/ true,
9582 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00009583 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00009584 return;
9585 }
9586
9587 // Fill in the rest of the conversions.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009588 unsigned NumParams = Proto->getNumParams();
John McCallfe796dd2010-01-23 05:17:32 +00009589 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009590 if (ArgIdx < NumParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009591 Cand->Conversions[ConvIdx] = TryCopyInitialization(
9592 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
9593 /*InOverloadResolution=*/true,
9594 /*AllowObjCWritebackConversion=*/
9595 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009596 // Store the FixIt in the candidate if it exists.
9597 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00009598 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009599 }
John McCallfe796dd2010-01-23 05:17:32 +00009600 else
9601 Cand->Conversions[ConvIdx].setEllipsis();
9602 }
9603}
9604
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009605/// PrintOverloadCandidates - When overload resolution fails, prints
9606/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00009607/// set.
John McCall5c32be02010-08-24 20:38:10 +00009608void OverloadCandidateSet::NoteCandidates(Sema &S,
9609 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009610 ArrayRef<Expr *> Args,
David Blaikie1d202a62012-10-08 01:11:04 +00009611 StringRef Opc,
John McCall5c32be02010-08-24 20:38:10 +00009612 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00009613 // Sort the candidates by viability and position. Sorting directly would
9614 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009615 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00009616 if (OCD == OCD_AllCandidates) Cands.reserve(size());
9617 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00009618 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00009619 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00009620 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009621 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009622 if (Cand->Function || Cand->IsSurrogate)
9623 Cands.push_back(Cand);
9624 // Otherwise, this a non-viable builtin candidate. We do not, in general,
9625 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00009626 }
9627 }
9628
John McCallad2587a2010-01-12 00:48:53 +00009629 std::sort(Cands.begin(), Cands.end(),
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009630 CompareOverloadCandidatesForDisplay(S, Args.size()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009631
John McCall0d1da222010-01-12 00:44:57 +00009632 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00009633
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009634 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +00009635 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009636 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00009637 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9638 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00009639
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009640 // Set an arbitrary limit on the number of candidate functions we'll spam
9641 // the user with. FIXME: This limit should depend on details of the
9642 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +00009643 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009644 break;
9645 }
9646 ++CandsShown;
9647
John McCalld3224162010-01-08 00:58:21 +00009648 if (Cand->Function)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009649 NoteFunctionCandidate(S, Cand, Args.size());
John McCalld3224162010-01-08 00:58:21 +00009650 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00009651 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009652 else {
9653 assert(Cand->Viable &&
9654 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00009655 // Generally we only see ambiguities including viable builtin
9656 // operators if overload resolution got screwed up by an
9657 // ambiguous user-defined conversion.
9658 //
9659 // FIXME: It's quite possible for different conversions to see
9660 // different ambiguities, though.
9661 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00009662 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00009663 ReportedAmbiguousConversions = true;
9664 }
John McCalld3224162010-01-08 00:58:21 +00009665
John McCall0d1da222010-01-12 00:44:57 +00009666 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00009667 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00009668 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009669 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009670
9671 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00009672 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009673}
9674
Larisse Voufo98b20f12013-07-19 23:00:19 +00009675static SourceLocation
9676GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9677 return Cand->Specialization ? Cand->Specialization->getLocation()
9678 : SourceLocation();
9679}
9680
Richard Smith17c00b42014-11-12 01:24:00 +00009681namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009682struct CompareTemplateSpecCandidatesForDisplay {
9683 Sema &S;
9684 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9685
9686 bool operator()(const TemplateSpecCandidate *L,
9687 const TemplateSpecCandidate *R) {
9688 // Fast-path this check.
9689 if (L == R)
9690 return false;
9691
9692 // Assuming that both candidates are not matches...
9693
9694 // Sort by the ranking of deduction failures.
9695 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9696 return RankDeductionFailure(L->DeductionFailure) <
9697 RankDeductionFailure(R->DeductionFailure);
9698
9699 // Sort everything else by location.
9700 SourceLocation LLoc = GetLocationForCandidate(L);
9701 SourceLocation RLoc = GetLocationForCandidate(R);
9702
9703 // Put candidates without locations (e.g. builtins) at the end.
9704 if (LLoc.isInvalid())
9705 return false;
9706 if (RLoc.isInvalid())
9707 return true;
9708
9709 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9710 }
9711};
Richard Smith17c00b42014-11-12 01:24:00 +00009712}
Larisse Voufo98b20f12013-07-19 23:00:19 +00009713
9714/// Diagnose a template argument deduction failure.
9715/// We are treating these failures as overload failures due to bad
9716/// deductions.
9717void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9718 DiagnoseBadDeduction(S, Specialization, // pattern
9719 DeductionFailure, /*NumArgs=*/0);
9720}
9721
9722void TemplateSpecCandidateSet::destroyCandidates() {
9723 for (iterator i = begin(), e = end(); i != e; ++i) {
9724 i->DeductionFailure.Destroy();
9725 }
9726}
9727
9728void TemplateSpecCandidateSet::clear() {
9729 destroyCandidates();
9730 Candidates.clear();
9731}
9732
9733/// NoteCandidates - When no template specialization match is found, prints
9734/// diagnostic messages containing the non-matching specializations that form
9735/// the candidate set.
9736/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9737/// OCD == OCD_AllCandidates and Cand->Viable == false.
9738void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9739 // Sort the candidates by position (assuming no candidate is a match).
9740 // Sorting directly would be prohibitive, so we make a set of pointers
9741 // and sort those.
9742 SmallVector<TemplateSpecCandidate *, 32> Cands;
9743 Cands.reserve(size());
9744 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9745 if (Cand->Specialization)
9746 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +00009747 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +00009748 // in general, want to list every possible builtin candidate.
9749 }
9750
9751 std::sort(Cands.begin(), Cands.end(),
9752 CompareTemplateSpecCandidatesForDisplay(S));
9753
9754 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9755 // for generalization purposes (?).
9756 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9757
9758 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9759 unsigned CandsShown = 0;
9760 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9761 TemplateSpecCandidate *Cand = *I;
9762
9763 // Set an arbitrary limit on the number of candidates we'll spam
9764 // the user with. FIXME: This limit should depend on details of the
9765 // candidate list.
9766 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9767 break;
9768 ++CandsShown;
9769
9770 assert(Cand->Specialization &&
9771 "Non-matching built-in candidates are not added to Cands.");
9772 Cand->NoteDeductionFailure(S);
9773 }
9774
9775 if (I != E)
9776 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9777}
9778
Douglas Gregorb491ed32011-02-19 21:32:49 +00009779// [PossiblyAFunctionType] --> [Return]
9780// NonFunctionType --> NonFunctionType
9781// R (A) --> R(A)
9782// R (*)(A) --> R (A)
9783// R (&)(A) --> R (A)
9784// R (S::*)(A) --> R (A)
9785QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9786 QualType Ret = PossiblyAFunctionType;
9787 if (const PointerType *ToTypePtr =
9788 PossiblyAFunctionType->getAs<PointerType>())
9789 Ret = ToTypePtr->getPointeeType();
9790 else if (const ReferenceType *ToTypeRef =
9791 PossiblyAFunctionType->getAs<ReferenceType>())
9792 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009793 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00009794 PossiblyAFunctionType->getAs<MemberPointerType>())
9795 Ret = MemTypePtr->getPointeeType();
9796 Ret =
9797 Context.getCanonicalType(Ret).getUnqualifiedType();
9798 return Ret;
9799}
Douglas Gregorcd695e52008-11-10 20:40:00 +00009800
Richard Smith17c00b42014-11-12 01:24:00 +00009801namespace {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009802// A helper class to help with address of function resolution
9803// - allows us to avoid passing around all those ugly parameters
Richard Smith17c00b42014-11-12 01:24:00 +00009804class AddressOfFunctionResolver {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009805 Sema& S;
9806 Expr* SourceExpr;
9807 const QualType& TargetType;
9808 QualType TargetFunctionType; // Extracted function type from target type
9809
9810 bool Complain;
9811 //DeclAccessPair& ResultFunctionAccessPair;
9812 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009813
Douglas Gregorb491ed32011-02-19 21:32:49 +00009814 bool TargetTypeIsNonStaticMemberFunction;
9815 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +00009816 bool StaticMemberFunctionFromBoundPointer;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009817
Douglas Gregorb491ed32011-02-19 21:32:49 +00009818 OverloadExpr::FindResult OvlExprInfo;
9819 OverloadExpr *OvlExpr;
9820 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009821 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009822 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009823
Douglas Gregorb491ed32011-02-19 21:32:49 +00009824public:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009825 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9826 const QualType &TargetType, bool Complain)
9827 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9828 Complain(Complain), Context(S.getASTContext()),
9829 TargetTypeIsNonStaticMemberFunction(
9830 !!TargetType->getAs<MemberPointerType>()),
9831 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +00009832 StaticMemberFunctionFromBoundPointer(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +00009833 OvlExprInfo(OverloadExpr::find(SourceExpr)),
9834 OvlExpr(OvlExprInfo.Expression),
9835 FailedCandidates(OvlExpr->getNameLoc()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009836 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +00009837
David Majnemera4f7c7a2013-08-01 06:13:59 +00009838 if (TargetFunctionType->isFunctionType()) {
9839 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9840 if (!UME->isImplicitAccess() &&
9841 !S.ResolveSingleFunctionTemplateSpecialization(UME))
9842 StaticMemberFunctionFromBoundPointer = true;
9843 } else if (OvlExpr->hasExplicitTemplateArgs()) {
9844 DeclAccessPair dap;
9845 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9846 OvlExpr, false, &dap)) {
9847 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9848 if (!Method->isStatic()) {
9849 // If the target type is a non-function type and the function found
9850 // is a non-static member function, pretend as if that was the
9851 // target, it's the only possible type to end up with.
9852 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +00009853
David Majnemera4f7c7a2013-08-01 06:13:59 +00009854 // And skip adding the function if its not in the proper form.
9855 // We'll diagnose this due to an empty set of functions.
9856 if (!OvlExprInfo.HasFormOfMemberPointer)
9857 return;
Chandler Carruthffce2452011-03-29 08:08:18 +00009858 }
9859
David Majnemera4f7c7a2013-08-01 06:13:59 +00009860 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +00009861 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009862 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00009863 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009864
9865 if (OvlExpr->hasExplicitTemplateArgs())
9866 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00009867
Douglas Gregorb491ed32011-02-19 21:32:49 +00009868 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9869 // C++ [over.over]p4:
9870 // If more than one function is selected, [...]
9871 if (Matches.size() > 1) {
9872 if (FoundNonTemplateFunction)
9873 EliminateAllTemplateMatches();
9874 else
9875 EliminateAllExceptMostSpecializedTemplate();
9876 }
9877 }
9878 }
9879
9880private:
9881 bool isTargetTypeAFunction() const {
9882 return TargetFunctionType->isFunctionType();
9883 }
9884
9885 // [ToType] [Return]
9886
9887 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9888 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9889 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9890 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9891 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9892 }
9893
9894 // return true if any matching specializations were found
9895 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9896 const DeclAccessPair& CurAccessFunPair) {
9897 if (CXXMethodDecl *Method
9898 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9899 // Skip non-static function templates when converting to pointer, and
9900 // static when converting to member pointer.
9901 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9902 return false;
9903 }
9904 else if (TargetTypeIsNonStaticMemberFunction)
9905 return false;
9906
9907 // C++ [over.over]p2:
9908 // If the name is a function template, template argument deduction is
9909 // done (14.8.2.2), and if the argument deduction succeeds, the
9910 // resulting template argument list is used to generate a single
9911 // function template specialization, which is added to the set of
9912 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +00009913 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009914 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +00009915 if (Sema::TemplateDeductionResult Result
9916 = S.DeduceTemplateArguments(FunctionTemplate,
9917 &OvlExplicitTemplateArgs,
9918 TargetFunctionType, Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00009919 Info, /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009920 // Make a note of the failed deduction for diagnostics.
9921 FailedCandidates.addCandidate()
9922 .set(FunctionTemplate->getTemplatedDecl(),
9923 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +00009924 return false;
9925 }
9926
Douglas Gregor19a41f12013-04-17 08:45:07 +00009927 // Template argument deduction ensures that we have an exact match or
9928 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009929 // This function template specicalization works.
9930 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Douglas Gregor19a41f12013-04-17 08:45:07 +00009931 assert(S.isSameOrCompatibleFunctionType(
9932 Context.getCanonicalType(Specialization->getType()),
9933 Context.getCanonicalType(TargetFunctionType)));
Douglas Gregorb491ed32011-02-19 21:32:49 +00009934 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9935 return true;
9936 }
9937
9938 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9939 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009940 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009941 // Skip non-static functions when converting to pointer, and static
9942 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009943 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9944 return false;
9945 }
9946 else if (TargetTypeIsNonStaticMemberFunction)
9947 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009948
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009949 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009950 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009951 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009952 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl))
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009953 return false;
9954
Richard Smith2a7d4812013-05-04 07:00:32 +00009955 // If any candidate has a placeholder return type, trigger its deduction
9956 // now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00009957 if (S.getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +00009958 FunDecl->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00009959 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
9960 return false;
9961
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00009962 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009963 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9964 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00009965 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9966 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009967 Matches.push_back(std::make_pair(CurAccessFunPair,
9968 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00009969 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009970 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00009971 }
Mike Stump11289f42009-09-09 15:08:12 +00009972 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009973
9974 return false;
9975 }
9976
9977 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9978 bool Ret = false;
9979
9980 // If the overload expression doesn't have the form of a pointer to
9981 // member, don't try to convert it to a pointer-to-member type.
9982 if (IsInvalidFormOfPointerToMemberFunction())
9983 return false;
9984
9985 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9986 E = OvlExpr->decls_end();
9987 I != E; ++I) {
9988 // Look through any using declarations to find the underlying function.
9989 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9990
9991 // C++ [over.over]p3:
9992 // Non-member functions and static member functions match
9993 // targets of type "pointer-to-function" or "reference-to-function."
9994 // Nonstatic member functions match targets of
9995 // type "pointer-to-member-function."
9996 // Note that according to DR 247, the containing class does not matter.
9997 if (FunctionTemplateDecl *FunctionTemplate
9998 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9999 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10000 Ret = true;
10001 }
10002 // If we have explicit template arguments supplied, skip non-templates.
10003 else if (!OvlExpr->hasExplicitTemplateArgs() &&
10004 AddMatchingNonTemplateFunction(Fn, I.getPair()))
10005 Ret = true;
10006 }
10007 assert(Ret || Matches.empty());
10008 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010009 }
10010
Douglas Gregorb491ed32011-02-19 21:32:49 +000010011 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +000010012 // [...] and any given function template specialization F1 is
10013 // eliminated if the set contains a second function template
10014 // specialization whose function template is more specialized
10015 // than the function template of F1 according to the partial
10016 // ordering rules of 14.5.5.2.
10017
10018 // The algorithm specified above is quadratic. We instead use a
10019 // two-pass algorithm (similar to the one used to identify the
10020 // best viable function in an overload set) that identifies the
10021 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +000010022
10023 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10024 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10025 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010026
Larisse Voufo98b20f12013-07-19 23:00:19 +000010027 // TODO: It looks like FailedCandidates does not serve much purpose
10028 // here, since the no_viable diagnostic has index 0.
10029 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +000010030 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010031 SourceExpr->getLocStart(), S.PDiag(),
10032 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
10033 .second->getDeclName(),
10034 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
10035 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010036
Douglas Gregorb491ed32011-02-19 21:32:49 +000010037 if (Result != MatchesCopy.end()) {
10038 // Make it the first and only element
10039 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10040 Matches[0].second = cast<FunctionDecl>(*Result);
10041 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +000010042 }
10043 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010044
Douglas Gregorb491ed32011-02-19 21:32:49 +000010045 void EliminateAllTemplateMatches() {
10046 // [...] any function template specializations in the set are
10047 // eliminated if the set also contains a non-template function, [...]
10048 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010049 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010050 ++I;
10051 else {
10052 Matches[I] = Matches[--N];
10053 Matches.set_size(N);
10054 }
10055 }
10056 }
10057
10058public:
10059 void ComplainNoMatchesFound() const {
10060 assert(Matches.empty());
10061 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10062 << OvlExpr->getName() << TargetFunctionType
10063 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +000010064 if (FailedCandidates.empty())
10065 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
10066 else {
10067 // We have some deduction failure messages. Use them to diagnose
10068 // the function templates, and diagnose the non-template candidates
10069 // normally.
10070 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10071 IEnd = OvlExpr->decls_end();
10072 I != IEnd; ++I)
10073 if (FunctionDecl *Fun =
10074 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
10075 S.NoteOverloadCandidate(Fun, TargetFunctionType);
10076 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10077 }
10078 }
10079
Douglas Gregorb491ed32011-02-19 21:32:49 +000010080 bool IsInvalidFormOfPointerToMemberFunction() const {
10081 return TargetTypeIsNonStaticMemberFunction &&
10082 !OvlExprInfo.HasFormOfMemberPointer;
10083 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010084
Douglas Gregorb491ed32011-02-19 21:32:49 +000010085 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10086 // TODO: Should we condition this on whether any functions might
10087 // have matched, or is it more appropriate to do that in callers?
10088 // TODO: a fixit wouldn't hurt.
10089 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10090 << TargetType << OvlExpr->getSourceRange();
10091 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010092
10093 bool IsStaticMemberFunctionFromBoundPointer() const {
10094 return StaticMemberFunctionFromBoundPointer;
10095 }
10096
10097 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10098 S.Diag(OvlExpr->getLocStart(),
10099 diag::err_invalid_form_pointer_member_function)
10100 << OvlExpr->getSourceRange();
10101 }
10102
Douglas Gregorb491ed32011-02-19 21:32:49 +000010103 void ComplainOfInvalidConversion() const {
10104 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10105 << OvlExpr->getName() << TargetType;
10106 }
10107
10108 void ComplainMultipleMatchesFound() const {
10109 assert(Matches.size() > 1);
10110 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10111 << OvlExpr->getName()
10112 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +000010113 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010114 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010115
10116 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10117
Douglas Gregorb491ed32011-02-19 21:32:49 +000010118 int getNumMatches() const { return Matches.size(); }
10119
10120 FunctionDecl* getMatchingFunctionDecl() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010121 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010122 return Matches[0].second;
10123 }
10124
10125 const DeclAccessPair* getMatchingFunctionAccessPair() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010126 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010127 return &Matches[0].first;
10128 }
10129};
Richard Smith17c00b42014-11-12 01:24:00 +000010130}
10131
Douglas Gregorb491ed32011-02-19 21:32:49 +000010132/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10133/// an overloaded function (C++ [over.over]), where @p From is an
10134/// expression with overloaded function type and @p ToType is the type
10135/// we're trying to resolve to. For example:
10136///
10137/// @code
10138/// int f(double);
10139/// int f(int);
10140///
10141/// int (*pfd)(double) = f; // selects f(double)
10142/// @endcode
10143///
10144/// This routine returns the resulting FunctionDecl if it could be
10145/// resolved, and NULL otherwise. When @p Complain is true, this
10146/// routine will emit diagnostics if there is an error.
10147FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010148Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10149 QualType TargetType,
10150 bool Complain,
10151 DeclAccessPair &FoundResult,
10152 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010153 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010154
10155 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10156 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010157 int NumMatches = Resolver.getNumMatches();
Craig Topperc3ec1492014-05-26 06:22:03 +000010158 FunctionDecl *Fn = nullptr;
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010159 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010160 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10161 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10162 else
10163 Resolver.ComplainNoMatchesFound();
10164 }
10165 else if (NumMatches > 1 && Complain)
10166 Resolver.ComplainMultipleMatchesFound();
10167 else if (NumMatches == 1) {
10168 Fn = Resolver.getMatchingFunctionDecl();
10169 assert(Fn);
10170 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +000010171 if (Complain) {
10172 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10173 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10174 else
10175 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10176 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +000010177 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010178
10179 if (pHadMultipleCandidates)
10180 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010181 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010182}
10183
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010184/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010185/// resolve that overloaded function expression down to a single function.
10186///
10187/// This routine can only resolve template-ids that refer to a single function
10188/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010189/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010190/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +000010191///
10192/// If no template-ids are found, no diagnostics are emitted and NULL is
10193/// returned.
John McCall0009fcc2011-04-26 20:42:42 +000010194FunctionDecl *
10195Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10196 bool Complain,
10197 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010198 // C++ [over.over]p1:
10199 // [...] [Note: any redundant set of parentheses surrounding the
10200 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010201 // C++ [over.over]p1:
10202 // [...] The overloaded function name can be preceded by the &
10203 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010204
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010205 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +000010206 if (!ovl->hasExplicitTemplateArgs())
Craig Topperc3ec1492014-05-26 06:22:03 +000010207 return nullptr;
John McCall1acbbb52010-02-02 06:20:04 +000010208
10209 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +000010210 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010211 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010212
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010213 // Look through all of the overloaded functions, searching for one
10214 // whose type matches exactly.
Craig Topperc3ec1492014-05-26 06:22:03 +000010215 FunctionDecl *Matched = nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010216 for (UnresolvedSetIterator I = ovl->decls_begin(),
10217 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010218 // C++0x [temp.arg.explicit]p3:
10219 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010220 // where deduction is not done, if a template argument list is
10221 // specified and it, along with any default template arguments,
10222 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010223 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +000010224 FunctionTemplateDecl *FunctionTemplate
10225 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010226
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010227 // C++ [over.over]p2:
10228 // If the name is a function template, template argument deduction is
10229 // done (14.8.2.2), and if the argument deduction succeeds, the
10230 // resulting template argument list is used to generate a single
10231 // function template specialization, which is added to the set of
10232 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010233 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010234 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010235 if (TemplateDeductionResult Result
10236 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000010237 Specialization, Info,
10238 /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010239 // Make a note of the failed deduction for diagnostics.
10240 // TODO: Actually use the failed-deduction info?
10241 FailedCandidates.addCandidate()
10242 .set(FunctionTemplate->getTemplatedDecl(),
10243 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010244 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010245 }
10246
John McCall0009fcc2011-04-26 20:42:42 +000010247 assert(Specialization && "no specialization and no error?");
10248
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010249 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010250 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010251 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000010252 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10253 << ovl->getName();
10254 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010255 }
Craig Topperc3ec1492014-05-26 06:22:03 +000010256 return nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010257 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010258
John McCall0009fcc2011-04-26 20:42:42 +000010259 Matched = Specialization;
10260 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010261 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010262
Aaron Ballmandd69ef32014-08-19 15:55:55 +000010263 if (Matched && getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +000010264 Matched->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +000010265 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
Craig Topperc3ec1492014-05-26 06:22:03 +000010266 return nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +000010267
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010268 return Matched;
10269}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010270
Douglas Gregor1beec452011-03-12 01:48:56 +000010271
10272
10273
John McCall50a2c2c2011-10-11 23:14:30 +000010274// Resolve and fix an overloaded expression that can be resolved
10275// because it identifies a single function template specialization.
10276//
Douglas Gregor1beec452011-03-12 01:48:56 +000010277// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000010278//
10279// Return true if it was logically possible to so resolve the
10280// expression, regardless of whether or not it succeeded. Always
10281// returns true if 'complain' is set.
10282bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10283 ExprResult &SrcExpr, bool doFunctionPointerConverion,
10284 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +000010285 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000010286 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000010287 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000010288
John McCall50a2c2c2011-10-11 23:14:30 +000010289 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000010290
John McCall0009fcc2011-04-26 20:42:42 +000010291 DeclAccessPair found;
10292 ExprResult SingleFunctionExpression;
10293 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10294 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010295 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000010296 SrcExpr = ExprError();
10297 return true;
10298 }
John McCall0009fcc2011-04-26 20:42:42 +000010299
10300 // It is only correct to resolve to an instance method if we're
10301 // resolving a form that's permitted to be a pointer to member.
10302 // Otherwise we'll end up making a bound member expression, which
10303 // is illegal in all the contexts we resolve like this.
10304 if (!ovl.HasFormOfMemberPointer &&
10305 isa<CXXMethodDecl>(fn) &&
10306 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000010307 if (!complain) return false;
10308
10309 Diag(ovl.Expression->getExprLoc(),
10310 diag::err_bound_member_function)
10311 << 0 << ovl.Expression->getSourceRange();
10312
10313 // TODO: I believe we only end up here if there's a mix of
10314 // static and non-static candidates (otherwise the expression
10315 // would have 'bound member' type, not 'overload' type).
10316 // Ideally we would note which candidate was chosen and why
10317 // the static candidates were rejected.
10318 SrcExpr = ExprError();
10319 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010320 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010321
Sylvestre Ledrua5202662012-07-31 06:56:50 +000010322 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000010323 SingleFunctionExpression =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010324 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall0009fcc2011-04-26 20:42:42 +000010325
10326 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000010327 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000010328 SingleFunctionExpression =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010329 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall50a2c2c2011-10-11 23:14:30 +000010330 if (SingleFunctionExpression.isInvalid()) {
10331 SrcExpr = ExprError();
10332 return true;
10333 }
10334 }
John McCall0009fcc2011-04-26 20:42:42 +000010335 }
10336
10337 if (!SingleFunctionExpression.isUsable()) {
10338 if (complain) {
10339 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10340 << ovl.Expression->getName()
10341 << DestTypeForComplaining
10342 << OpRangeForComplaining
10343 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000010344 NoteAllOverloadCandidates(SrcExpr.get());
10345
10346 SrcExpr = ExprError();
10347 return true;
10348 }
10349
10350 return false;
John McCall0009fcc2011-04-26 20:42:42 +000010351 }
10352
John McCall50a2c2c2011-10-11 23:14:30 +000010353 SrcExpr = SingleFunctionExpression;
10354 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010355}
10356
Douglas Gregorcabea402009-09-22 15:41:20 +000010357/// \brief Add a single candidate to the overload set.
10358static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000010359 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000010360 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010361 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010362 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000010363 bool PartialOverloading,
10364 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000010365 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000010366 if (isa<UsingShadowDecl>(Callee))
10367 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10368
Douglas Gregorcabea402009-09-22 15:41:20 +000010369 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000010370 if (ExplicitTemplateArgs) {
10371 assert(!KnownValid && "Explicit template arguments?");
10372 return;
10373 }
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010374 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
10375 /*SuppressUsedConversions=*/false,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010376 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010377 return;
John McCalld14a8642009-11-21 08:51:07 +000010378 }
10379
10380 if (FunctionTemplateDecl *FuncTemplate
10381 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000010382 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010383 ExplicitTemplateArgs, Args, CandidateSet,
10384 /*SuppressUsedConversions=*/false,
10385 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +000010386 return;
10387 }
10388
Richard Smith95ce4f62011-06-26 22:19:54 +000010389 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000010390}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010391
Douglas Gregorcabea402009-09-22 15:41:20 +000010392/// \brief Add the overload candidates named by callee and/or found by argument
10393/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000010394void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010395 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010396 OverloadCandidateSet &CandidateSet,
10397 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000010398
10399#ifndef NDEBUG
10400 // Verify that ArgumentDependentLookup is consistent with the rules
10401 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000010402 //
Douglas Gregorcabea402009-09-22 15:41:20 +000010403 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10404 // and let Y be the lookup set produced by argument dependent
10405 // lookup (defined as follows). If X contains
10406 //
10407 // -- a declaration of a class member, or
10408 //
10409 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000010410 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000010411 //
10412 // -- a declaration that is neither a function or a function
10413 // template
10414 //
10415 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000010416
John McCall57500772009-12-16 12:17:52 +000010417 if (ULE->requiresADL()) {
10418 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10419 E = ULE->decls_end(); I != E; ++I) {
10420 assert(!(*I)->getDeclContext()->isRecord());
10421 assert(isa<UsingShadowDecl>(*I) ||
10422 !(*I)->getDeclContext()->isFunctionOrMethod());
10423 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000010424 }
10425 }
10426#endif
10427
John McCall57500772009-12-16 12:17:52 +000010428 // It would be nice to avoid this copy.
10429 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000010430 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000010431 if (ULE->hasExplicitTemplateArgs()) {
10432 ULE->copyTemplateArgumentsInto(TABuffer);
10433 ExplicitTemplateArgs = &TABuffer;
10434 }
10435
10436 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10437 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010438 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10439 CandidateSet, PartialOverloading,
10440 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000010441
John McCall57500772009-12-16 12:17:52 +000010442 if (ULE->requiresADL())
Richard Smith100b24a2014-04-17 01:52:14 +000010443 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010444 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000010445 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010446}
John McCalld681c392009-12-16 08:11:27 +000010447
Richard Smith0603bbb2013-06-12 22:56:54 +000010448/// Determine whether a declaration with the specified name could be moved into
10449/// a different namespace.
10450static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10451 switch (Name.getCXXOverloadedOperator()) {
10452 case OO_New: case OO_Array_New:
10453 case OO_Delete: case OO_Array_Delete:
10454 return false;
10455
10456 default:
10457 return true;
10458 }
10459}
10460
Richard Smith998a5912011-06-05 22:42:48 +000010461/// Attempt to recover from an ill-formed use of a non-dependent name in a
10462/// template, where the non-dependent name was declared after the template
10463/// was defined. This is common in code written for a compilers which do not
10464/// correctly implement two-stage name lookup.
10465///
10466/// Returns true if a viable candidate was found and a diagnostic was issued.
10467static bool
10468DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10469 const CXXScopeSpec &SS, LookupResult &R,
Richard Smith100b24a2014-04-17 01:52:14 +000010470 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smith998a5912011-06-05 22:42:48 +000010471 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010472 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000010473 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10474 return false;
10475
10476 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000010477 if (DC->isTransparentContext())
10478 continue;
10479
Richard Smith998a5912011-06-05 22:42:48 +000010480 SemaRef.LookupQualifiedName(R, DC);
10481
10482 if (!R.empty()) {
10483 R.suppressDiagnostics();
10484
10485 if (isa<CXXRecordDecl>(DC)) {
10486 // Don't diagnose names we find in classes; we get much better
10487 // diagnostics for these from DiagnoseEmptyLookup.
10488 R.clear();
10489 return false;
10490 }
10491
Richard Smith100b24a2014-04-17 01:52:14 +000010492 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smith998a5912011-06-05 22:42:48 +000010493 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10494 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010495 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000010496 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000010497
10498 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000010499 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000010500 // No viable functions. Don't bother the user with notes for functions
10501 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000010502 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000010503 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000010504 }
Richard Smith998a5912011-06-05 22:42:48 +000010505
10506 // Find the namespaces where ADL would have looked, and suggest
10507 // declaring the function there instead.
10508 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10509 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000010510 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000010511 AssociatedNamespaces,
10512 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000010513 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000010514 if (canBeDeclaredInNamespace(R.getLookupName())) {
10515 DeclContext *Std = SemaRef.getStdNamespace();
10516 for (Sema::AssociatedNamespaceSet::iterator
10517 it = AssociatedNamespaces.begin(),
10518 end = AssociatedNamespaces.end(); it != end; ++it) {
10519 // Never suggest declaring a function within namespace 'std'.
10520 if (Std && Std->Encloses(*it))
10521 continue;
Richard Smith21bae432012-12-22 02:46:14 +000010522
Richard Smith0603bbb2013-06-12 22:56:54 +000010523 // Never suggest declaring a function within a namespace with a
10524 // reserved name, like __gnu_cxx.
10525 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10526 if (NS &&
10527 NS->getQualifiedNameAsString().find("__") != std::string::npos)
10528 continue;
10529
10530 SuggestedNamespaces.insert(*it);
10531 }
Richard Smith998a5912011-06-05 22:42:48 +000010532 }
10533
10534 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10535 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000010536 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000010537 SemaRef.Diag(Best->Function->getLocation(),
10538 diag::note_not_found_by_two_phase_lookup)
10539 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000010540 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000010541 SemaRef.Diag(Best->Function->getLocation(),
10542 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000010543 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000010544 } else {
10545 // FIXME: It would be useful to list the associated namespaces here,
10546 // but the diagnostics infrastructure doesn't provide a way to produce
10547 // a localized representation of a list of items.
10548 SemaRef.Diag(Best->Function->getLocation(),
10549 diag::note_not_found_by_two_phase_lookup)
10550 << R.getLookupName() << 2;
10551 }
10552
10553 // Try to recover by calling this function.
10554 return true;
10555 }
10556
10557 R.clear();
10558 }
10559
10560 return false;
10561}
10562
10563/// Attempt to recover from ill-formed use of a non-dependent operator in a
10564/// template, where the non-dependent operator was declared after the template
10565/// was defined.
10566///
10567/// Returns true if a viable candidate was found and a diagnostic was issued.
10568static bool
10569DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10570 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010571 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000010572 DeclarationName OpName =
10573 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10574 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10575 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Richard Smith100b24a2014-04-17 01:52:14 +000010576 OverloadCandidateSet::CSK_Operator,
Craig Topperc3ec1492014-05-26 06:22:03 +000010577 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smith998a5912011-06-05 22:42:48 +000010578}
10579
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010580namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000010581class BuildRecoveryCallExprRAII {
10582 Sema &SemaRef;
10583public:
10584 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10585 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10586 SemaRef.IsBuildingRecoveryCallExpr = true;
10587 }
10588
10589 ~BuildRecoveryCallExprRAII() {
10590 SemaRef.IsBuildingRecoveryCallExpr = false;
10591 }
10592};
10593
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010594}
10595
Kaelyn Takata89c881b2014-10-27 18:07:29 +000010596static std::unique_ptr<CorrectionCandidateCallback>
10597MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
10598 bool HasTemplateArgs, bool AllowTypoCorrection) {
10599 if (!AllowTypoCorrection)
10600 return llvm::make_unique<NoTypoCorrectionCCC>();
10601 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
10602 HasTemplateArgs, ME);
10603}
10604
John McCalld681c392009-12-16 08:11:27 +000010605/// Attempts to recover from a call where no functions were found.
10606///
10607/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000010608static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000010609BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000010610 UnresolvedLookupExpr *ULE,
10611 SourceLocation LParenLoc,
Craig Toppere3d2ecbe2014-06-28 23:22:33 +000010612 MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000010613 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010614 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000010615 // Do not try to recover if it is already building a recovery call.
10616 // This stops infinite loops for template instantiations like
10617 //
10618 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10619 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10620 //
10621 if (SemaRef.IsBuildingRecoveryCallExpr)
10622 return ExprError();
10623 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000010624
10625 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000010626 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000010627 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000010628
John McCall57500772009-12-16 12:17:52 +000010629 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000010630 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000010631 if (ULE->hasExplicitTemplateArgs()) {
10632 ULE->copyTemplateArgumentsInto(TABuffer);
10633 ExplicitTemplateArgs = &TABuffer;
10634 }
10635
John McCalld681c392009-12-16 08:11:27 +000010636 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10637 Sema::LookupOrdinaryName);
Richard Smith998a5912011-06-05 22:42:48 +000010638 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Richard Smith100b24a2014-04-17 01:52:14 +000010639 OverloadCandidateSet::CSK_Normal,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010640 ExplicitTemplateArgs, Args) &&
Richard Smith998a5912011-06-05 22:42:48 +000010641 (!EmptyLookup ||
Kaelyn Takata89c881b2014-10-27 18:07:29 +000010642 SemaRef.DiagnoseEmptyLookup(
10643 S, SS, R,
10644 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
10645 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
10646 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000010647 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000010648
John McCall57500772009-12-16 12:17:52 +000010649 assert(!R.empty() && "lookup results empty despite recovery");
10650
10651 // Build an implicit member call if appropriate. Just drop the
10652 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000010653 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000010654 if ((*R.begin())->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +000010655 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
10656 R, ExplicitTemplateArgs);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000010657 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000010658 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000010659 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000010660 else
10661 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10662
10663 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000010664 return ExprError();
John McCall57500772009-12-16 12:17:52 +000010665
10666 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000010667 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000010668 // end up here.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010669 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010670 MultiExprArg(Args.data(), Args.size()),
10671 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000010672}
Douglas Gregor4038cf42010-06-08 17:35:15 +000010673
Sam Panzer0f384432012-08-21 00:52:01 +000010674/// \brief Constructs and populates an OverloadedCandidateSet from
10675/// the given function.
10676/// \returns true when an the ExprResult output parameter has been set.
10677bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10678 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010679 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010680 SourceLocation RParenLoc,
10681 OverloadCandidateSet *CandidateSet,
10682 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000010683#ifndef NDEBUG
10684 if (ULE->requiresADL()) {
10685 // To do ADL, we must have found an unqualified name.
10686 assert(!ULE->getQualifier() && "qualified name with ADL");
10687
10688 // We don't perform ADL for implicit declarations of builtins.
10689 // Verify that this was correctly set up.
10690 FunctionDecl *F;
10691 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10692 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10693 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000010694 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010695
John McCall57500772009-12-16 12:17:52 +000010696 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010697 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000010698 }
John McCall57500772009-12-16 12:17:52 +000010699#endif
10700
John McCall4124c492011-10-17 18:40:02 +000010701 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010702 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000010703 *Result = ExprError();
10704 return true;
10705 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000010706
John McCall57500772009-12-16 12:17:52 +000010707 // Add the functions denoted by the callee to the set of candidate
10708 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010709 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000010710
10711 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +000010712 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
10713 // out if it fails.
Sam Panzer0f384432012-08-21 00:52:01 +000010714 if (CandidateSet->empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010715 // In Microsoft mode, if we are inside a template class member function then
10716 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +000010717 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010718 // classes.
Alp Tokerbfa39342014-01-14 12:51:41 +000010719 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
Francois Pichetde232cb2011-11-25 01:10:54 +000010720 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010721 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args,
Benjamin Kramerc215e762012-08-24 11:54:20 +000010722 Context.DependentTy, VK_RValue,
10723 RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010724 CE->setTypeDependent(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010725 *Result = CE;
Sam Panzer0f384432012-08-21 00:52:01 +000010726 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010727 }
Sam Panzer0f384432012-08-21 00:52:01 +000010728 return false;
Francois Pichetbcf64712011-09-07 00:14:57 +000010729 }
John McCalld681c392009-12-16 08:11:27 +000010730
John McCall4124c492011-10-17 18:40:02 +000010731 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000010732 return false;
10733}
John McCall4124c492011-10-17 18:40:02 +000010734
Sam Panzer0f384432012-08-21 00:52:01 +000010735/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10736/// the completed call expression. If overload resolution fails, emits
10737/// diagnostics and returns ExprError()
10738static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10739 UnresolvedLookupExpr *ULE,
10740 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010741 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010742 SourceLocation RParenLoc,
10743 Expr *ExecConfig,
10744 OverloadCandidateSet *CandidateSet,
10745 OverloadCandidateSet::iterator *Best,
10746 OverloadingResult OverloadResult,
10747 bool AllowTypoCorrection) {
10748 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010749 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010750 RParenLoc, /*EmptyLookup=*/true,
10751 AllowTypoCorrection);
10752
10753 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000010754 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000010755 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000010756 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000010757 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10758 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000010759 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010760 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10761 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000010762 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010763
Richard Smith998a5912011-06-05 22:42:48 +000010764 case OR_No_Viable_Function: {
10765 // Try to recover by looking for viable functions which the user might
10766 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000010767 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010768 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010769 /*EmptyLookup=*/false,
10770 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000010771 if (!Recovery.isInvalid())
10772 return Recovery;
10773
Sam Panzer0f384432012-08-21 00:52:01 +000010774 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010775 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +000010776 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010777 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010778 break;
Richard Smith998a5912011-06-05 22:42:48 +000010779 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010780
10781 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000010782 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000010783 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010784 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010785 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000010786
Sam Panzer0f384432012-08-21 00:52:01 +000010787 case OR_Deleted: {
10788 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10789 << (*Best)->Function->isDeleted()
10790 << ULE->getName()
10791 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10792 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010793 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000010794
Sam Panzer0f384432012-08-21 00:52:01 +000010795 // We emitted an error for the unvailable/deleted function call but keep
10796 // the call in the AST.
10797 FunctionDecl *FDecl = (*Best)->Function;
10798 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010799 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10800 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000010801 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010802 }
10803
Douglas Gregorb412e172010-07-25 18:17:45 +000010804 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000010805 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010806}
10807
Sam Panzer0f384432012-08-21 00:52:01 +000010808/// BuildOverloadedCallExpr - Given the call expression that calls Fn
10809/// (which eventually refers to the declaration Func) and the call
10810/// arguments Args/NumArgs, attempt to resolve the function call down
10811/// to a specific function. If overload resolution succeeds, returns
10812/// the call expression produced by overload resolution.
10813/// Otherwise, emits diagnostics and returns ExprError.
10814ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10815 UnresolvedLookupExpr *ULE,
10816 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010817 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010818 SourceLocation RParenLoc,
10819 Expr *ExecConfig,
10820 bool AllowTypoCorrection) {
Richard Smith100b24a2014-04-17 01:52:14 +000010821 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
10822 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000010823 ExprResult result;
10824
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010825 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10826 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000010827 return result;
10828
10829 OverloadCandidateSet::iterator Best;
10830 OverloadingResult OverloadResult =
10831 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10832
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010833 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010834 RParenLoc, ExecConfig, &CandidateSet,
10835 &Best, OverloadResult,
10836 AllowTypoCorrection);
10837}
10838
John McCall4c4c1df2010-01-26 03:27:55 +000010839static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000010840 return Functions.size() > 1 ||
10841 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10842}
10843
Douglas Gregor084d8552009-03-13 23:49:33 +000010844/// \brief Create a unary operation that may resolve to an overloaded
10845/// operator.
10846///
10847/// \param OpLoc The location of the operator itself (e.g., '*').
10848///
10849/// \param OpcIn The UnaryOperator::Opcode that describes this
10850/// operator.
10851///
James Dennett18348b62012-06-22 08:52:37 +000010852/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000010853/// considered by overload resolution. The caller needs to build this
10854/// set based on the context using, e.g.,
10855/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10856/// set should not contain any member functions; those will be added
10857/// by CreateOverloadedUnaryOp().
10858///
James Dennett91738ff2012-06-22 10:32:46 +000010859/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000010860ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +000010861Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10862 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +000010863 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010864 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +000010865
10866 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10867 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10868 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010869 // TODO: provide better source location info.
10870 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000010871
John McCall4124c492011-10-17 18:40:02 +000010872 if (checkPlaceholderForOverload(*this, Input))
10873 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010874
Craig Topperc3ec1492014-05-26 06:22:03 +000010875 Expr *Args[2] = { Input, nullptr };
Douglas Gregor084d8552009-03-13 23:49:33 +000010876 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000010877
Douglas Gregor084d8552009-03-13 23:49:33 +000010878 // For post-increment and post-decrement, add the implicit '0' as
10879 // the second argument, so that we know this is a post-increment or
10880 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000010881 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010882 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000010883 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10884 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000010885 NumArgs = 2;
10886 }
10887
Richard Smithe54c3072013-05-05 15:51:06 +000010888 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10889
Douglas Gregor084d8552009-03-13 23:49:33 +000010890 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000010891 if (Fns.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010892 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
10893 VK_RValue, OK_Ordinary, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010894
Craig Topperc3ec1492014-05-26 06:22:03 +000010895 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000010896 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000010897 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000010898 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010899 /*ADL*/ true, IsOverloaded(Fns),
10900 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010901 return new (Context)
10902 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
10903 VK_RValue, OpLoc, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000010904 }
10905
10906 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000010907 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor084d8552009-03-13 23:49:33 +000010908
10909 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010910 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010911
10912 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000010913 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010914
John McCall4c4c1df2010-01-26 03:27:55 +000010915 // Add candidates from ADL.
Richard Smith100b24a2014-04-17 01:52:14 +000010916 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
Craig Topperc3ec1492014-05-26 06:22:03 +000010917 /*ExplicitTemplateArgs*/nullptr,
10918 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000010919
Douglas Gregor084d8552009-03-13 23:49:33 +000010920 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000010921 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010922
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010923 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10924
Douglas Gregor084d8552009-03-13 23:49:33 +000010925 // Perform overload resolution.
10926 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010927 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010928 case OR_Success: {
10929 // We found a built-in operator or an overloaded operator.
10930 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000010931
Douglas Gregor084d8552009-03-13 23:49:33 +000010932 if (FnDecl) {
10933 // We matched an overloaded operator. Build a call to that
10934 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000010935
Douglas Gregor084d8552009-03-13 23:49:33 +000010936 // Convert the arguments.
10937 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010938 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000010939
John Wiegley01296292011-04-08 18:41:53 +000010940 ExprResult InputRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000010941 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000010942 Best->FoundDecl, Method);
10943 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000010944 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010945 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000010946 } else {
10947 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000010948 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000010949 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010950 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000010951 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010952 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000010953 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000010954 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000010955 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010956 Input = InputInit.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000010957 }
10958
Douglas Gregor084d8552009-03-13 23:49:33 +000010959 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000010960 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010961 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010962 if (FnExpr.isInvalid())
10963 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000010964
Richard Smithc1564702013-11-15 02:58:23 +000010965 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000010966 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000010967 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10968 ResultTy = ResultTy.getNonLValueExprType(Context);
10969
Eli Friedman030eee42009-11-18 03:58:17 +000010970 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000010971 CallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010972 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Lang Hames5de91cc2012-10-02 04:45:10 +000010973 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000010974
Alp Toker314cc812014-01-25 16:55:45 +000010975 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000010976 return ExprError();
10977
John McCallb268a282010-08-23 23:25:46 +000010978 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000010979 } else {
10980 // We matched a built-in operator. Convert the arguments, then
10981 // break out so that we will build the appropriate built-in
10982 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010983 ExprResult InputRes =
10984 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10985 Best->Conversions[0], AA_Passing);
10986 if (InputRes.isInvalid())
10987 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010988 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000010989 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000010990 }
John Wiegley01296292011-04-08 18:41:53 +000010991 }
10992
10993 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000010994 // This is an erroneous use of an operator which can be overloaded by
10995 // a non-member function. Check for non-member operators which were
10996 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000010997 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000010998 // FIXME: Recover by calling the found function.
10999 return ExprError();
11000
John Wiegley01296292011-04-08 18:41:53 +000011001 // No viable function; fall through to handling this as a
11002 // built-in operator, which will produce an error message for us.
11003 break;
11004
11005 case OR_Ambiguous:
11006 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11007 << UnaryOperator::getOpcodeStr(Opc)
11008 << Input->getType()
11009 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011010 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000011011 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11012 return ExprError();
11013
11014 case OR_Deleted:
11015 Diag(OpLoc, diag::err_ovl_deleted_oper)
11016 << Best->Function->isDeleted()
11017 << UnaryOperator::getOpcodeStr(Opc)
11018 << getDeletedOrUnavailableSuffix(Best->Function)
11019 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011020 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011021 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011022 return ExprError();
11023 }
Douglas Gregor084d8552009-03-13 23:49:33 +000011024
11025 // Either we found no viable overloaded operator or we matched a
11026 // built-in operator. In either case, fall through to trying to
11027 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000011028 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000011029}
11030
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011031/// \brief Create a binary operation that may resolve to an overloaded
11032/// operator.
11033///
11034/// \param OpLoc The location of the operator itself (e.g., '+').
11035///
11036/// \param OpcIn The BinaryOperator::Opcode that describes this
11037/// operator.
11038///
James Dennett18348b62012-06-22 08:52:37 +000011039/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011040/// considered by overload resolution. The caller needs to build this
11041/// set based on the context using, e.g.,
11042/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11043/// set should not contain any member functions; those will be added
11044/// by CreateOverloadedBinOp().
11045///
11046/// \param LHS Left-hand argument.
11047/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000011048ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011049Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +000011050 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +000011051 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011052 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011053 Expr *Args[2] = { LHS, RHS };
Craig Topperc3ec1492014-05-26 06:22:03 +000011054 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011055
11056 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
11057 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11058 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11059
11060 // If either side is type-dependent, create an appropriate dependent
11061 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000011062 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000011063 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011064 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000011065 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000011066 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011067 return new (Context) BinaryOperator(
11068 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11069 OpLoc, FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011070
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011071 return new (Context) CompoundAssignOperator(
11072 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11073 Context.DependentTy, Context.DependentTy, OpLoc,
11074 FPFeatures.fp_contract);
Douglas Gregor5287f092009-11-05 00:51:44 +000011075 }
John McCall4c4c1df2010-01-26 03:27:55 +000011076
11077 // FIXME: save results of ADL from here?
Craig Topperc3ec1492014-05-26 06:22:03 +000011078 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011079 // TODO: provide better source location info in DNLoc component.
11080 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000011081 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000011082 = UnresolvedLookupExpr::Create(Context, NamingClass,
11083 NestedNameSpecifierLoc(), OpNameInfo,
11084 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011085 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011086 return new (Context)
11087 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11088 VK_RValue, OpLoc, FPFeatures.fp_contract);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011089 }
11090
John McCall4124c492011-10-17 18:40:02 +000011091 // Always do placeholder-like conversions on the RHS.
11092 if (checkPlaceholderForOverload(*this, Args[1]))
11093 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011094
John McCall526ab472011-10-25 17:37:35 +000011095 // Do placeholder-like conversion on the LHS; note that we should
11096 // not get here with a PseudoObject LHS.
11097 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000011098 if (checkPlaceholderForOverload(*this, Args[0]))
11099 return ExprError();
11100
Sebastian Redl6a96bf72009-11-18 23:10:33 +000011101 // If this is the assignment operator, we only perform overload resolution
11102 // if the left-hand side is a class or enumeration type. This is actually
11103 // a hack. The standard requires that we do overload resolution between the
11104 // various built-in candidates, but as DR507 points out, this can lead to
11105 // problems. So we do it this way, which pretty much follows what GCC does.
11106 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000011107 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000011108 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011109
John McCalle26a8722010-12-04 08:14:53 +000011110 // If this is the .* operator, which is not overloadable, just
11111 // create a built-in binary operator.
11112 if (Opc == BO_PtrMemD)
11113 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11114
Douglas Gregor084d8552009-03-13 23:49:33 +000011115 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011116 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011117
11118 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011119 AddFunctionCandidates(Fns, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011120
11121 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011122 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011123
Richard Smith0daabd72014-09-23 20:31:39 +000011124 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11125 // performed for an assignment operator (nor for operator[] nor operator->,
11126 // which don't get here).
11127 if (Opc != BO_Assign)
11128 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11129 /*ExplicitTemplateArgs*/ nullptr,
11130 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011131
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011132 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011133 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011134
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011135 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11136
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011137 // Perform overload resolution.
11138 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011139 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000011140 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011141 // We found a built-in operator or an overloaded operator.
11142 FunctionDecl *FnDecl = Best->Function;
11143
11144 if (FnDecl) {
11145 // We matched an overloaded operator. Build a call to that
11146 // operator.
11147
11148 // Convert the arguments.
11149 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000011150 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000011151 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011152
Chandler Carruth8e543b32010-12-12 08:17:55 +000011153 ExprResult Arg1 =
11154 PerformCopyInitialization(
11155 InitializedEntity::InitializeParameter(Context,
11156 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011157 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011158 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011159 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011160
John Wiegley01296292011-04-08 18:41:53 +000011161 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011162 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011163 Best->FoundDecl, Method);
11164 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011165 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011166 Args[0] = Arg0.getAs<Expr>();
11167 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011168 } else {
11169 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000011170 ExprResult Arg0 = PerformCopyInitialization(
11171 InitializedEntity::InitializeParameter(Context,
11172 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011173 SourceLocation(), Args[0]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011174 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011175 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011176
Chandler Carruth8e543b32010-12-12 08:17:55 +000011177 ExprResult Arg1 =
11178 PerformCopyInitialization(
11179 InitializedEntity::InitializeParameter(Context,
11180 FnDecl->getParamDecl(1)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011181 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011182 if (Arg1.isInvalid())
11183 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011184 Args[0] = LHS = Arg0.getAs<Expr>();
11185 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011186 }
11187
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011188 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011189 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011190 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011191 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011192 if (FnExpr.isInvalid())
11193 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011194
Richard Smithc1564702013-11-15 02:58:23 +000011195 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011196 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011197 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11198 ResultTy = ResultTy.getNonLValueExprType(Context);
11199
John McCallb268a282010-08-23 23:25:46 +000011200 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011201 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000011202 Args, ResultTy, VK, OpLoc,
11203 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011204
Alp Toker314cc812014-01-25 16:55:45 +000011205 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011206 FnDecl))
11207 return ExprError();
11208
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011209 ArrayRef<const Expr *> ArgsArray(Args, 2);
11210 // Cut off the implicit 'this'.
11211 if (isa<CXXMethodDecl>(FnDecl))
11212 ArgsArray = ArgsArray.slice(1);
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011213
11214 // Check for a self move.
11215 if (Op == OO_Equal)
11216 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11217
11218 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011219 TheCall->getSourceRange(), VariadicDoesNotApply);
11220
John McCallb268a282010-08-23 23:25:46 +000011221 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011222 } else {
11223 // We matched a built-in operator. Convert the arguments, then
11224 // break out so that we will build the appropriate built-in
11225 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011226 ExprResult ArgsRes0 =
11227 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11228 Best->Conversions[0], AA_Passing);
11229 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011230 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011231 Args[0] = ArgsRes0.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011232
John Wiegley01296292011-04-08 18:41:53 +000011233 ExprResult ArgsRes1 =
11234 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11235 Best->Conversions[1], AA_Passing);
11236 if (ArgsRes1.isInvalid())
11237 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011238 Args[1] = ArgsRes1.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011239 break;
11240 }
11241 }
11242
Douglas Gregor66950a32009-09-30 21:46:01 +000011243 case OR_No_Viable_Function: {
11244 // C++ [over.match.oper]p9:
11245 // If the operator is the operator , [...] and there are no
11246 // viable functions, then the operator is assumed to be the
11247 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000011248 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000011249 break;
11250
Chandler Carruth8e543b32010-12-12 08:17:55 +000011251 // For class as left operand for assignment or compound assigment
11252 // operator do not fall through to handling in built-in, but report that
11253 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000011254 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011255 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000011256 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000011257 Diag(OpLoc, diag::err_ovl_no_viable_oper)
11258 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000011259 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000011260 if (Args[0]->getType()->isIncompleteType()) {
11261 Diag(OpLoc, diag::note_assign_lhs_incomplete)
11262 << Args[0]->getType()
11263 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11264 }
Douglas Gregor66950a32009-09-30 21:46:01 +000011265 } else {
Richard Smith998a5912011-06-05 22:42:48 +000011266 // This is an erroneous use of an operator which can be overloaded by
11267 // a non-member function. Check for non-member operators which were
11268 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011269 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000011270 // FIXME: Recover by calling the found function.
11271 return ExprError();
11272
Douglas Gregor66950a32009-09-30 21:46:01 +000011273 // No viable function; try to create a built-in operation, which will
11274 // produce an error. Then, show the non-viable candidates.
11275 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000011276 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011277 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000011278 "C++ binary operator overloading is missing candidates!");
11279 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011280 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011281 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011282 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000011283 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011284
11285 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011286 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011287 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000011288 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000011289 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011290 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011291 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011292 return ExprError();
11293
11294 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000011295 if (isImplicitlyDeleted(Best->Function)) {
11296 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11297 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000011298 << Context.getRecordType(Method->getParent())
11299 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000011300
Richard Smithde1a4872012-12-28 12:23:24 +000011301 // The user probably meant to call this special member. Just
11302 // explain why it's deleted.
11303 NoteDeletedFunction(Method);
11304 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000011305 } else {
11306 Diag(OpLoc, diag::err_ovl_deleted_oper)
11307 << Best->Function->isDeleted()
11308 << BinaryOperator::getOpcodeStr(Opc)
11309 << getDeletedOrUnavailableSuffix(Best->Function)
11310 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11311 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011312 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011313 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011314 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000011315 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011316
Douglas Gregor66950a32009-09-30 21:46:01 +000011317 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000011318 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011319}
11320
John McCalldadc5752010-08-24 06:29:42 +000011321ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000011322Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11323 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000011324 Expr *Base, Expr *Idx) {
11325 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000011326 DeclarationName OpName =
11327 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11328
11329 // If either side is type-dependent, create an appropriate dependent
11330 // expression.
11331 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11332
Craig Topperc3ec1492014-05-26 06:22:03 +000011333 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011334 // CHECKME: no 'operator' keyword?
11335 DeclarationNameInfo OpNameInfo(OpName, LLoc);
11336 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000011337 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011338 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011339 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011340 /*ADL*/ true, /*Overloaded*/ false,
11341 UnresolvedSetIterator(),
11342 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000011343 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000011344
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011345 return new (Context)
11346 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11347 Context.DependentTy, VK_RValue, RLoc, false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011348 }
11349
John McCall4124c492011-10-17 18:40:02 +000011350 // Handle placeholders on both operands.
11351 if (checkPlaceholderForOverload(*this, Args[0]))
11352 return ExprError();
11353 if (checkPlaceholderForOverload(*this, Args[1]))
11354 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011355
Sebastian Redladba46e2009-10-29 20:17:01 +000011356 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011357 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redladba46e2009-10-29 20:17:01 +000011358
11359 // Subscript can only be overloaded as a member function.
11360
11361 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011362 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011363
11364 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011365 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011366
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011367 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11368
Sebastian Redladba46e2009-10-29 20:17:01 +000011369 // Perform overload resolution.
11370 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011371 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000011372 case OR_Success: {
11373 // We found a built-in operator or an overloaded operator.
11374 FunctionDecl *FnDecl = Best->Function;
11375
11376 if (FnDecl) {
11377 // We matched an overloaded operator. Build a call to that
11378 // operator.
11379
John McCalla0296f72010-03-19 07:35:19 +000011380 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000011381
Sebastian Redladba46e2009-10-29 20:17:01 +000011382 // Convert the arguments.
11383 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000011384 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011385 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011386 Best->FoundDecl, Method);
11387 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011388 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011389 Args[0] = Arg0.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011390
Anders Carlssona68e51e2010-01-29 18:37:50 +000011391 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011392 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000011393 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011394 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000011395 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011396 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011397 Args[1]);
Anders Carlssona68e51e2010-01-29 18:37:50 +000011398 if (InputInit.isInvalid())
11399 return ExprError();
11400
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011401 Args[1] = InputInit.getAs<Expr>();
Anders Carlssona68e51e2010-01-29 18:37:50 +000011402
Sebastian Redladba46e2009-10-29 20:17:01 +000011403 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011404 DeclarationNameInfo OpLocInfo(OpName, LLoc);
11405 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011406 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011407 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011408 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011409 OpLocInfo.getLoc(),
11410 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011411 if (FnExpr.isInvalid())
11412 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011413
Richard Smithc1564702013-11-15 02:58:23 +000011414 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000011415 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011416 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11417 ResultTy = ResultTy.getNonLValueExprType(Context);
11418
John McCallb268a282010-08-23 23:25:46 +000011419 CXXOperatorCallExpr *TheCall =
11420 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011421 FnExpr.get(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000011422 ResultTy, VK, RLoc,
11423 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011424
Alp Toker314cc812014-01-25 16:55:45 +000011425 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000011426 return ExprError();
11427
John McCallb268a282010-08-23 23:25:46 +000011428 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000011429 } else {
11430 // We matched a built-in operator. Convert the arguments, then
11431 // break out so that we will build the appropriate built-in
11432 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011433 ExprResult ArgsRes0 =
11434 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11435 Best->Conversions[0], AA_Passing);
11436 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011437 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011438 Args[0] = ArgsRes0.get();
John Wiegley01296292011-04-08 18:41:53 +000011439
11440 ExprResult ArgsRes1 =
11441 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11442 Best->Conversions[1], AA_Passing);
11443 if (ArgsRes1.isInvalid())
11444 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011445 Args[1] = ArgsRes1.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011446
11447 break;
11448 }
11449 }
11450
11451 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000011452 if (CandidateSet.empty())
11453 Diag(LLoc, diag::err_ovl_no_oper)
11454 << Args[0]->getType() << /*subscript*/ 0
11455 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11456 else
11457 Diag(LLoc, diag::err_ovl_no_viable_subscript)
11458 << Args[0]->getType()
11459 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011460 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011461 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000011462 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011463 }
11464
11465 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011466 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011467 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000011468 << Args[0]->getType() << Args[1]->getType()
11469 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011470 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011471 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011472 return ExprError();
11473
11474 case OR_Deleted:
11475 Diag(LLoc, diag::err_ovl_deleted_oper)
11476 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011477 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000011478 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011479 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011480 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011481 return ExprError();
11482 }
11483
11484 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000011485 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011486}
11487
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011488/// BuildCallToMemberFunction - Build a call to a member
11489/// function. MemExpr is the expression that refers to the member
11490/// function (and includes the object parameter), Args/NumArgs are the
11491/// arguments to the function call (not including the object
11492/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000011493/// expression refers to a non-static member function or an overloaded
11494/// member function.
John McCalldadc5752010-08-24 06:29:42 +000011495ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000011496Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011497 SourceLocation LParenLoc,
11498 MultiExprArg Args,
11499 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000011500 assert(MemExprE->getType() == Context.BoundMemberTy ||
11501 MemExprE->getType() == Context.OverloadTy);
11502
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011503 // Dig out the member expression. This holds both the object
11504 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000011505 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011506
John McCall0009fcc2011-04-26 20:42:42 +000011507 // Determine whether this is a call to a pointer-to-member function.
11508 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11509 assert(op->getType() == Context.BoundMemberTy);
11510 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
11511
11512 QualType fnType =
11513 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11514
11515 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11516 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000011517 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000011518
11519 // Check that the object type isn't more qualified than the
11520 // member function we're calling.
11521 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11522
11523 QualType objectType = op->getLHS()->getType();
11524 if (op->getOpcode() == BO_PtrMemI)
11525 objectType = objectType->castAs<PointerType>()->getPointeeType();
11526 Qualifiers objectQuals = objectType.getQualifiers();
11527
11528 Qualifiers difference = objectQuals - funcQuals;
11529 difference.removeObjCGCAttr();
11530 difference.removeAddressSpace();
11531 if (difference) {
11532 std::string qualsString = difference.getAsString();
11533 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11534 << fnType.getUnqualifiedType()
11535 << qualsString
11536 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11537 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011538
David Majnemerb3e56542014-08-07 22:56:13 +000011539 if (resultType->isMemberPointerType())
11540 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11541 RequireCompleteType(LParenLoc, resultType, 0);
11542
John McCall0009fcc2011-04-26 20:42:42 +000011543 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011544 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000011545 resultType, valueKind, RParenLoc);
11546
Alp Toker314cc812014-01-25 16:55:45 +000011547 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +000011548 call, nullptr))
John McCall0009fcc2011-04-26 20:42:42 +000011549 return ExprError();
11550
Craig Topperc3ec1492014-05-26 06:22:03 +000011551 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000011552 return ExprError();
11553
Richard Trieu9be9c682013-06-22 02:30:38 +000011554 if (CheckOtherCall(call, proto))
11555 return ExprError();
11556
John McCall0009fcc2011-04-26 20:42:42 +000011557 return MaybeBindToTemporary(call);
11558 }
11559
John McCall4124c492011-10-17 18:40:02 +000011560 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011561 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000011562 return ExprError();
11563
John McCall10eae182009-11-30 22:42:35 +000011564 MemberExpr *MemExpr;
Craig Topperc3ec1492014-05-26 06:22:03 +000011565 CXXMethodDecl *Method = nullptr;
11566 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
11567 NestedNameSpecifier *Qualifier = nullptr;
John McCall10eae182009-11-30 22:42:35 +000011568 if (isa<MemberExpr>(NakedMemExpr)) {
11569 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000011570 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000011571 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011572 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000011573 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000011574 } else {
11575 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011576 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011577
John McCall6e9f8f62009-12-03 04:06:58 +000011578 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000011579 Expr::Classification ObjectClassification
11580 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11581 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000011582
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011583 // Add overload candidates
Richard Smith100b24a2014-04-17 01:52:14 +000011584 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
11585 OverloadCandidateSet::CSK_Normal);
Mike Stump11289f42009-09-09 15:08:12 +000011586
John McCall2d74de92009-12-01 22:10:20 +000011587 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000011588 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000011589 if (UnresExpr->hasExplicitTemplateArgs()) {
11590 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11591 TemplateArgs = &TemplateArgsBuffer;
11592 }
11593
John McCall10eae182009-11-30 22:42:35 +000011594 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11595 E = UnresExpr->decls_end(); I != E; ++I) {
11596
John McCall6e9f8f62009-12-03 04:06:58 +000011597 NamedDecl *Func = *I;
11598 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11599 if (isa<UsingShadowDecl>(Func))
11600 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11601
Douglas Gregor02824322011-01-26 19:30:28 +000011602
Francois Pichet64225792011-01-18 05:04:39 +000011603 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011604 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011605 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011606 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000011607 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000011608 // If explicit template arguments were provided, we can't call a
11609 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000011610 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000011611 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011612
John McCalla0296f72010-03-19 07:35:19 +000011613 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011614 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000011615 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000011616 } else {
John McCall10eae182009-11-30 22:42:35 +000011617 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000011618 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011619 ObjectType, ObjectClassification,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011620 Args, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000011621 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000011622 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000011623 }
Mike Stump11289f42009-09-09 15:08:12 +000011624
John McCall10eae182009-11-30 22:42:35 +000011625 DeclarationName DeclName = UnresExpr->getMemberName();
11626
John McCall4124c492011-10-17 18:40:02 +000011627 UnbridgedCasts.restore();
11628
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011629 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011630 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000011631 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011632 case OR_Success:
11633 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000011634 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000011635 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011636 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11637 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000011638 // If FoundDecl is different from Method (such as if one is a template
11639 // and the other a specialization), make sure DiagnoseUseOfDecl is
11640 // called on both.
11641 // FIXME: This would be more comprehensively addressed by modifying
11642 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11643 // being used.
11644 if (Method != FoundDecl.getDecl() &&
11645 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11646 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011647 break;
11648
11649 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000011650 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011651 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000011652 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011653 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011654 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011655 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011656
11657 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000011658 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000011659 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011660 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011661 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011662 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000011663
11664 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000011665 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000011666 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011667 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011668 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011669 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011670 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000011671 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011672 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011673 }
11674
John McCall16df1e52010-03-30 21:47:33 +000011675 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000011676
John McCall2d74de92009-12-01 22:10:20 +000011677 // If overload resolution picked a static member, build a
11678 // non-member call based on that function.
11679 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011680 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11681 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000011682 }
11683
John McCall10eae182009-11-30 22:42:35 +000011684 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011685 }
11686
Alp Toker314cc812014-01-25 16:55:45 +000011687 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000011688 ExprValueKind VK = Expr::getValueKindForType(ResultType);
11689 ResultType = ResultType.getNonLValueExprType(Context);
11690
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011691 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011692 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011693 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000011694 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011695
Eli Bendersky291a57e2014-09-25 23:59:08 +000011696 // (CUDA B.1): Check for invalid calls between targets.
11697 if (getLangOpts().CUDA) {
11698 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
11699 if (CheckCUDATarget(Caller, Method)) {
11700 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
11701 << IdentifyCUDATarget(Method) << Method->getIdentifier()
11702 << IdentifyCUDATarget(Caller);
11703 return ExprError();
11704 }
11705 }
11706 }
11707
Anders Carlssonc4859ba2009-10-10 00:06:20 +000011708 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000011709 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000011710 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000011711 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011712
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011713 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000011714 // We only need to do this if there was actually an overload; otherwise
11715 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000011716 if (!Method->isStatic()) {
11717 ExprResult ObjectArg =
11718 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11719 FoundDecl, Method);
11720 if (ObjectArg.isInvalid())
11721 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011722 MemExpr->setBase(ObjectArg.get());
John Wiegley01296292011-04-08 18:41:53 +000011723 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011724
11725 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000011726 const FunctionProtoType *Proto =
11727 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011728 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011729 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000011730 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011731
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011732 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011733
Richard Smith55ce3522012-06-25 20:30:08 +000011734 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000011735 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000011736
Anders Carlsson47061ee2011-05-06 14:25:31 +000011737 if ((isa<CXXConstructorDecl>(CurContext) ||
11738 isa<CXXDestructorDecl>(CurContext)) &&
11739 TheCall->getMethodDecl()->isPure()) {
11740 const CXXMethodDecl *MD = TheCall->getMethodDecl();
11741
Chandler Carruth59259262011-06-27 08:31:58 +000011742 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +000011743 Diag(MemExpr->getLocStart(),
11744 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11745 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11746 << MD->getParent()->getDeclName();
11747
11748 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000011749 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000011750 }
John McCallb268a282010-08-23 23:25:46 +000011751 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011752}
11753
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011754/// BuildCallToObjectOfClassType - Build a call to an object of class
11755/// type (C++ [over.call.object]), which can end up invoking an
11756/// overloaded function call operator (@c operator()) or performing a
11757/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000011758ExprResult
John Wiegley01296292011-04-08 18:41:53 +000011759Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000011760 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011761 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011762 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000011763 if (checkPlaceholderForOverload(*this, Obj))
11764 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011765 ExprResult Object = Obj;
John McCall4124c492011-10-17 18:40:02 +000011766
11767 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011768 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000011769 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011770
Nico Weberb58e51c2014-11-19 05:21:39 +000011771 assert(Object.get()->getType()->isRecordType() &&
11772 "Requires object type argument");
John Wiegley01296292011-04-08 18:41:53 +000011773 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000011774
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011775 // C++ [over.call.object]p1:
11776 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000011777 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011778 // candidate functions includes at least the function call
11779 // operators of T. The function call operators of T are obtained by
11780 // ordinary lookup of the name operator() in the context of
11781 // (E).operator().
Richard Smith100b24a2014-04-17 01:52:14 +000011782 OverloadCandidateSet CandidateSet(LParenLoc,
11783 OverloadCandidateSet::CSK_Operator);
Douglas Gregor91f84212008-12-11 16:49:14 +000011784 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011785
John Wiegley01296292011-04-08 18:41:53 +000011786 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011787 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011788 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011789
John McCall27b18f82009-11-17 02:14:36 +000011790 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11791 LookupQualifiedName(R, Record->getDecl());
11792 R.suppressDiagnostics();
11793
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011794 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000011795 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000011796 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011797 Object.get()->Classify(Context),
11798 Args, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000011799 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000011800 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011801
Douglas Gregorab7897a2008-11-19 22:57:39 +000011802 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011803 // In addition, for each (non-explicit in C++0x) conversion function
11804 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000011805 //
11806 // operator conversion-type-id () cv-qualifier;
11807 //
11808 // where cv-qualifier is the same cv-qualification as, or a
11809 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000011810 // denotes the type "pointer to function of (P1,...,Pn) returning
11811 // R", or the type "reference to pointer to function of
11812 // (P1,...,Pn) returning R", or the type "reference to function
11813 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000011814 // is also considered as a candidate function. Similarly,
11815 // surrogate call functions are added to the set of candidate
11816 // functions for each conversion function declared in an
11817 // accessible base class provided the function is not hidden
11818 // within T by another intervening declaration.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000011819 std::pair<CXXRecordDecl::conversion_iterator,
11820 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregor21591822010-01-11 19:36:35 +000011821 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000011822 for (CXXRecordDecl::conversion_iterator
11823 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000011824 NamedDecl *D = *I;
11825 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11826 if (isa<UsingShadowDecl>(D))
11827 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011828
Douglas Gregor74ba25c2009-10-21 06:18:39 +000011829 // Skip over templated conversion functions; they aren't
11830 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000011831 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000011832 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000011833
John McCall6e9f8f62009-12-03 04:06:58 +000011834 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011835 if (!Conv->isExplicit()) {
11836 // Strip the reference type (if any) and then the pointer type (if
11837 // any) to get down to what might be a function type.
11838 QualType ConvType = Conv->getConversionType().getNonReferenceType();
11839 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11840 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000011841
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011842 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11843 {
11844 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011845 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011846 }
11847 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000011848 }
Mike Stump11289f42009-09-09 15:08:12 +000011849
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011850 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11851
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011852 // Perform overload resolution.
11853 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000011854 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000011855 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011856 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000011857 // Overload resolution succeeded; we'll build the appropriate call
11858 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011859 break;
11860
11861 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000011862 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011863 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000011864 << Object.get()->getType() << /*call*/ 1
11865 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000011866 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011867 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000011868 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000011869 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011870 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011871 break;
11872
11873 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011874 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011875 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000011876 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011877 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011878 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011879
11880 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011881 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000011882 diag::err_ovl_deleted_object_call)
11883 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000011884 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011885 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000011886 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011887 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000011888 break;
Mike Stump11289f42009-09-09 15:08:12 +000011889 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011890
Douglas Gregorb412e172010-07-25 18:17:45 +000011891 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011892 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011893
John McCall4124c492011-10-17 18:40:02 +000011894 UnbridgedCasts.restore();
11895
Craig Topperc3ec1492014-05-26 06:22:03 +000011896 if (Best->Function == nullptr) {
Douglas Gregorab7897a2008-11-19 22:57:39 +000011897 // Since there is no function declaration, this is one of the
11898 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000011899 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000011900 = cast<CXXConversionDecl>(
11901 Best->Conversions[0].UserDefined.ConversionFunction);
11902
Craig Topperc3ec1492014-05-26 06:22:03 +000011903 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
11904 Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011905 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11906 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000011907 assert(Conv == Best->FoundDecl.getDecl() &&
11908 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000011909 // We selected one of the surrogate functions that converts the
11910 // object parameter to a function pointer. Perform the conversion
11911 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011912
Fariborz Jahanian774cf792009-09-28 18:35:46 +000011913 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000011914 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011915 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11916 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000011917 if (Call.isInvalid())
11918 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000011919 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011920 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
11921 CK_UserDefinedConversion, Call.get(),
11922 nullptr, VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011923
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011924 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000011925 }
11926
Craig Topperc3ec1492014-05-26 06:22:03 +000011927 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000011928
Douglas Gregorab7897a2008-11-19 22:57:39 +000011929 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11930 // that calls this method, using Object for the implicit object
11931 // parameter and passing along the remaining arguments.
11932 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000011933
11934 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000011935 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000011936 return ExprError();
11937
Chandler Carruth8e543b32010-12-12 08:17:55 +000011938 const FunctionProtoType *Proto =
11939 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011940
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011941 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000011942
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011943 DeclarationNameInfo OpLocInfo(
11944 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11945 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000011946 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011947 HadMultipleCandidates,
11948 OpLocInfo.getLoc(),
11949 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011950 if (NewFn.isInvalid())
11951 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011952
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000011953 // Build the full argument list for the method call (the implicit object
11954 // parameter is placed at the beginning of the list).
Ahmed Charlesaf94d562014-03-09 11:34:25 +000011955 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000011956 MethodArgs[0] = Object.get();
11957 std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
11958
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011959 // Once we've built TheCall, all of the expressions are properly
11960 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000011961 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000011962 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11963 ResultTy = ResultTy.getNonLValueExprType(Context);
11964
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000011965 CXXOperatorCallExpr *TheCall = new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011966 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000011967 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
11968 ResultTy, VK, RParenLoc, false);
11969 MethodArgs.reset();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011970
Alp Toker314cc812014-01-25 16:55:45 +000011971 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000011972 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011973
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011974 // We may have default arguments. If so, we need to allocate more
11975 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011976 if (Args.size() < NumParams)
11977 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011978
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011979 bool IsError = false;
11980
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011981 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000011982 ExprResult ObjRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000011983 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011984 Best->FoundDecl, Method);
11985 if (ObjRes.isInvalid())
11986 IsError = true;
11987 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011988 Object = ObjRes;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011989 TheCall->setArg(0, Object.get());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011990
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011991 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011992 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011993 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011994 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011995 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000011996
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011997 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011998
John McCalldadc5752010-08-24 06:29:42 +000011999 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012000 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012001 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012002 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000012003 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012004
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012005 IsError |= InputInit.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012006 Arg = InputInit.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012007 } else {
John McCalldadc5752010-08-24 06:29:42 +000012008 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000012009 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12010 if (DefArg.isInvalid()) {
12011 IsError = true;
12012 break;
12013 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012014
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012015 Arg = DefArg.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012016 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012017
12018 TheCall->setArg(i + 1, Arg);
12019 }
12020
12021 // If this is a variadic call, handle args passed through "...".
12022 if (Proto->isVariadic()) {
12023 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012024 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012025 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12026 nullptr);
John Wiegley01296292011-04-08 18:41:53 +000012027 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012028 TheCall->setArg(i + 1, Arg.get());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012029 }
12030 }
12031
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012032 if (IsError) return true;
12033
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012034 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012035
Richard Smith55ce3522012-06-25 20:30:08 +000012036 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000012037 return true;
12038
John McCalle172be52010-08-24 06:09:16 +000012039 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012040}
12041
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012042/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000012043/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012044/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000012045ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012046Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12047 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000012048 assert(Base->getType()->isRecordType() &&
12049 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000012050
John McCall4124c492011-10-17 18:40:02 +000012051 if (checkPlaceholderForOverload(*this, Base))
12052 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012053
John McCallbc077cf2010-02-08 23:07:23 +000012054 SourceLocation Loc = Base->getExprLoc();
12055
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012056 // C++ [over.ref]p1:
12057 //
12058 // [...] An expression x->m is interpreted as (x.operator->())->m
12059 // for a class object x of type T if T::operator->() exists and if
12060 // the operator is selected as the best match function by the
12061 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000012062 DeclarationName OpName =
12063 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Richard Smith100b24a2014-04-17 01:52:14 +000012064 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000012065 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000012066
John McCallbc077cf2010-02-08 23:07:23 +000012067 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012068 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000012069 return ExprError();
12070
John McCall27b18f82009-11-17 02:14:36 +000012071 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12072 LookupQualifiedName(R, BaseRecord->getDecl());
12073 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000012074
12075 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000012076 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000012077 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000012078 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000012079 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012080
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012081 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12082
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012083 // Perform overload resolution.
12084 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012085 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012086 case OR_Success:
12087 // Overload resolution succeeded; we'll build the call below.
12088 break;
12089
12090 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012091 if (CandidateSet.empty()) {
12092 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012093 if (NoArrowOperatorFound) {
12094 // Report this specific error to the caller instead of emitting a
12095 // diagnostic, as requested.
12096 *NoArrowOperatorFound = true;
12097 return ExprError();
12098 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012099 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12100 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012101 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012102 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012103 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012104 }
12105 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012106 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000012107 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012108 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012109 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012110
12111 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012112 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12113 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012114 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012115 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012116
12117 case OR_Deleted:
12118 Diag(OpLoc, diag::err_ovl_deleted_oper)
12119 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012120 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012121 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012122 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012123 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012124 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012125 }
12126
Craig Topperc3ec1492014-05-26 06:22:03 +000012127 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCalla0296f72010-03-19 07:35:19 +000012128
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012129 // Convert the object parameter.
12130 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000012131 ExprResult BaseResult =
Craig Topperc3ec1492014-05-26 06:22:03 +000012132 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012133 Best->FoundDecl, Method);
12134 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000012135 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012136 Base = BaseResult.get();
Douglas Gregor9ecea262008-11-21 03:04:22 +000012137
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012138 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000012139 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012140 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012141 if (FnExpr.isInvalid())
12142 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012143
Alp Toker314cc812014-01-25 16:55:45 +000012144 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012145 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12146 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000012147 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012148 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012149 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012150
Alp Toker314cc812014-01-25 16:55:45 +000012151 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012152 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000012153
12154 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012155}
12156
Richard Smithbcc22fc2012-03-09 08:00:36 +000012157/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12158/// a literal operator described by the provided lookup results.
12159ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12160 DeclarationNameInfo &SuffixInfo,
12161 ArrayRef<Expr*> Args,
12162 SourceLocation LitEndLoc,
12163 TemplateArgumentListInfo *TemplateArgs) {
12164 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000012165
Richard Smith100b24a2014-04-17 01:52:14 +000012166 OverloadCandidateSet CandidateSet(UDSuffixLoc,
12167 OverloadCandidateSet::CSK_Normal);
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000012168 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12169 /*SuppressUserConversions=*/true);
Richard Smithc67fdd42012-03-07 08:35:16 +000012170
Richard Smithbcc22fc2012-03-09 08:00:36 +000012171 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12172
Richard Smithbcc22fc2012-03-09 08:00:36 +000012173 // Perform overload resolution. This will usually be trivial, but might need
12174 // to perform substitutions for a literal operator template.
12175 OverloadCandidateSet::iterator Best;
12176 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12177 case OR_Success:
12178 case OR_Deleted:
12179 break;
12180
12181 case OR_No_Viable_Function:
12182 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12183 << R.getLookupName();
12184 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12185 return ExprError();
12186
12187 case OR_Ambiguous:
12188 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12189 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12190 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000012191 }
12192
Richard Smithbcc22fc2012-03-09 08:00:36 +000012193 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000012194 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12195 HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000012196 SuffixInfo.getLoc(),
12197 SuffixInfo.getInfo());
12198 if (Fn.isInvalid())
12199 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000012200
12201 // Check the argument types. This should almost always be a no-op, except
12202 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000012203 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000012204 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000012205 ExprResult InputInit = PerformCopyInitialization(
12206 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12207 SourceLocation(), Args[ArgIdx]);
12208 if (InputInit.isInvalid())
12209 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012210 ConvArgs[ArgIdx] = InputInit.get();
Richard Smithc67fdd42012-03-07 08:35:16 +000012211 }
12212
Alp Toker314cc812014-01-25 16:55:45 +000012213 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000012214 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12215 ResultTy = ResultTy.getNonLValueExprType(Context);
12216
Richard Smithc67fdd42012-03-07 08:35:16 +000012217 UserDefinedLiteral *UDL =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012218 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000012219 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000012220 ResultTy, VK, LitEndLoc, UDSuffixLoc);
12221
Alp Toker314cc812014-01-25 16:55:45 +000012222 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000012223 return ExprError();
12224
Craig Topperc3ec1492014-05-26 06:22:03 +000012225 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smithc67fdd42012-03-07 08:35:16 +000012226 return ExprError();
12227
12228 return MaybeBindToTemporary(UDL);
12229}
12230
Sam Panzer0f384432012-08-21 00:52:01 +000012231/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12232/// given LookupResult is non-empty, it is assumed to describe a member which
12233/// will be invoked. Otherwise, the function will be found via argument
12234/// dependent lookup.
12235/// CallExpr is set to a valid expression and FRS_Success returned on success,
12236/// otherwise CallExpr is set to ExprError() and some non-success value
12237/// is returned.
12238Sema::ForRangeStatus
12239Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
12240 SourceLocation RangeLoc, VarDecl *Decl,
12241 BeginEndFunction BEF,
12242 const DeclarationNameInfo &NameInfo,
12243 LookupResult &MemberLookup,
12244 OverloadCandidateSet *CandidateSet,
12245 Expr *Range, ExprResult *CallExpr) {
12246 CandidateSet->clear();
12247 if (!MemberLookup.empty()) {
12248 ExprResult MemberRef =
12249 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12250 /*IsPtr=*/false, CXXScopeSpec(),
12251 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012252 /*FirstQualifierInScope=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012253 MemberLookup,
Craig Topperc3ec1492014-05-26 06:22:03 +000012254 /*TemplateArgs=*/nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000012255 if (MemberRef.isInvalid()) {
12256 *CallExpr = ExprError();
12257 Diag(Range->getLocStart(), diag::note_in_for_range)
12258 << RangeLoc << BEF << Range->getType();
12259 return FRS_DiagnosticIssued;
12260 }
Craig Topperc3ec1492014-05-26 06:22:03 +000012261 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000012262 if (CallExpr->isInvalid()) {
12263 *CallExpr = ExprError();
12264 Diag(Range->getLocStart(), diag::note_in_for_range)
12265 << RangeLoc << BEF << Range->getType();
12266 return FRS_DiagnosticIssued;
12267 }
12268 } else {
12269 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000012270 UnresolvedLookupExpr *Fn =
Craig Topperc3ec1492014-05-26 06:22:03 +000012271 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012272 NestedNameSpecifierLoc(), NameInfo,
12273 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000012274 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000012275
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012276 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000012277 CandidateSet, CallExpr);
12278 if (CandidateSet->empty() || CandidateSetError) {
12279 *CallExpr = ExprError();
12280 return FRS_NoViableFunction;
12281 }
12282 OverloadCandidateSet::iterator Best;
12283 OverloadingResult OverloadResult =
12284 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12285
12286 if (OverloadResult == OR_No_Viable_Function) {
12287 *CallExpr = ExprError();
12288 return FRS_NoViableFunction;
12289 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012290 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Craig Topperc3ec1492014-05-26 06:22:03 +000012291 Loc, nullptr, CandidateSet, &Best,
Sam Panzer0f384432012-08-21 00:52:01 +000012292 OverloadResult,
12293 /*AllowTypoCorrection=*/false);
12294 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12295 *CallExpr = ExprError();
12296 Diag(Range->getLocStart(), diag::note_in_for_range)
12297 << RangeLoc << BEF << Range->getType();
12298 return FRS_DiagnosticIssued;
12299 }
12300 }
12301 return FRS_Success;
12302}
12303
12304
Douglas Gregorcd695e52008-11-10 20:40:00 +000012305/// FixOverloadedFunctionReference - E is an expression that refers to
12306/// a C++ overloaded function (possibly with some parentheses and
12307/// perhaps a '&' around it). We have resolved the overloaded function
12308/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000012309/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000012310Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000012311 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000012312 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012313 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12314 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012315 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012316 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012317
Douglas Gregor51c538b2009-11-20 19:42:02 +000012318 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012319 }
12320
Douglas Gregor51c538b2009-11-20 19:42:02 +000012321 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012322 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12323 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012324 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000012325 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000012326 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000012327 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000012328 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012329 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012330
12331 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000012332 ICE->getCastKind(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012333 SubExpr, nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000012334 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012335 }
12336
Douglas Gregor51c538b2009-11-20 19:42:02 +000012337 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000012338 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000012339 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012340 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12341 if (Method->isStatic()) {
12342 // Do nothing: static member functions aren't any different
12343 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000012344 } else {
Alp Toker028ed912013-12-06 17:56:43 +000012345 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000012346 // UnresolvedLookupExpr holding an overloaded member function
12347 // or template.
John McCall16df1e52010-03-30 21:47:33 +000012348 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12349 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000012350 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012351 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012352
John McCalld14a8642009-11-21 08:51:07 +000012353 assert(isa<DeclRefExpr>(SubExpr)
12354 && "fixed to something other than a decl ref");
12355 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12356 && "fixed to a member ref with no nested name qualifier");
12357
12358 // We have taken the address of a pointer to member
12359 // function. Perform the computation here so that we get the
12360 // appropriate pointer to member type.
12361 QualType ClassType
12362 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12363 QualType MemPtrType
12364 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12365
John McCall7decc9e2010-11-18 06:31:45 +000012366 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12367 VK_RValue, OK_Ordinary,
12368 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012369 }
12370 }
John McCall16df1e52010-03-30 21:47:33 +000012371 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12372 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012373 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012374 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012375
John McCalle3027922010-08-25 11:45:40 +000012376 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012377 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000012378 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012379 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012380 }
John McCalld14a8642009-11-21 08:51:07 +000012381
12382 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000012383 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012384 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCalle66edc12009-11-24 19:00:30 +000012385 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000012386 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12387 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000012388 }
12389
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012390 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12391 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012392 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012393 Fn,
John McCall113bee02012-03-10 09:33:50 +000012394 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012395 ULE->getNameLoc(),
12396 Fn->getType(),
12397 VK_LValue,
12398 Found.getDecl(),
12399 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012400 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012401 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12402 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000012403 }
12404
John McCall10eae182009-11-30 22:42:35 +000012405 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000012406 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012407 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012408 if (MemExpr->hasExplicitTemplateArgs()) {
12409 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12410 TemplateArgs = &TemplateArgsBuffer;
12411 }
John McCall6b51f282009-11-23 01:53:49 +000012412
John McCall2d74de92009-12-01 22:10:20 +000012413 Expr *Base;
12414
John McCall7decc9e2010-11-18 06:31:45 +000012415 // If we're filling in a static method where we used to have an
12416 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000012417 if (MemExpr->isImplicitAccess()) {
12418 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012419 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12420 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012421 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012422 Fn,
John McCall113bee02012-03-10 09:33:50 +000012423 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012424 MemExpr->getMemberLoc(),
12425 Fn->getType(),
12426 VK_LValue,
12427 Found.getDecl(),
12428 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012429 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012430 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
12431 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000012432 } else {
12433 SourceLocation Loc = MemExpr->getMemberLoc();
12434 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000012435 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000012436 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000012437 Base = new (Context) CXXThisExpr(Loc,
12438 MemExpr->getBaseType(),
12439 /*isImplicit=*/true);
12440 }
John McCall2d74de92009-12-01 22:10:20 +000012441 } else
John McCallc3007a22010-10-26 07:05:15 +000012442 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000012443
John McCall4adb38c2011-04-27 00:36:17 +000012444 ExprValueKind valueKind;
12445 QualType type;
12446 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12447 valueKind = VK_LValue;
12448 type = Fn->getType();
12449 } else {
12450 valueKind = VK_RValue;
12451 type = Context.BoundMemberTy;
12452 }
12453
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012454 MemberExpr *ME = MemberExpr::Create(Context, Base,
12455 MemExpr->isArrow(),
12456 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012457 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012458 Fn,
12459 Found,
12460 MemExpr->getMemberNameInfo(),
12461 TemplateArgs,
12462 type, valueKind, OK_Ordinary);
12463 ME->setHadMultipleCandidates(true);
Richard Smith4f6a2c42012-11-14 07:06:31 +000012464 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012465 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012466 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012467
John McCallc3007a22010-10-26 07:05:15 +000012468 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000012469}
12470
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012471ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000012472 DeclAccessPair Found,
12473 FunctionDecl *Fn) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012474 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor3e1e5272009-12-09 23:02:17 +000012475}