blob: 34a03abb96fb8865c29b2c85dc9e7a22101ee496 [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) {
Richard Smith64ecacf2015-02-19 00:39:05 +0000289 // 'bool' is an integral type; dispatch to the right place to handle it.
290 case ICK_Boolean_Conversion:
291 if (FromType->isRealFloatingType())
292 goto FloatingIntegralConversion;
293 if (FromType->isIntegralOrUnscopedEnumerationType())
294 goto IntegralConversion;
295 // Boolean conversions can be from pointers and pointers to members
296 // [conv.bool], and those aren't considered narrowing conversions.
297 return NK_Not_Narrowing;
298
Richard Smith66e05fe2012-01-18 05:21:49 +0000299 // -- from a floating-point type to an integer type, or
300 //
301 // -- from an integer type or unscoped enumeration type to a floating-point
302 // type, except where the source is a constant expression and the actual
303 // value after conversion will fit into the target type and will produce
304 // the original value when converted back to the original type, or
305 case ICK_Floating_Integral:
Richard Smith64ecacf2015-02-19 00:39:05 +0000306 FloatingIntegralConversion:
Richard Smith66e05fe2012-01-18 05:21:49 +0000307 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
308 return NK_Type_Narrowing;
309 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
310 llvm::APSInt IntConstantValue;
311 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
312 if (Initializer &&
313 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
314 // Convert the integer to the floating type.
315 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
316 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
317 llvm::APFloat::rmNearestTiesToEven);
318 // And back.
319 llvm::APSInt ConvertedValue = IntConstantValue;
320 bool ignored;
321 Result.convertToInteger(ConvertedValue,
322 llvm::APFloat::rmTowardZero, &ignored);
323 // If the resulting value is different, this was a narrowing conversion.
324 if (IntConstantValue != ConvertedValue) {
325 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000326 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000327 return NK_Constant_Narrowing;
328 }
329 } else {
330 // Variables are always narrowings.
331 return NK_Variable_Narrowing;
332 }
333 }
334 return NK_Not_Narrowing;
335
336 // -- from long double to double or float, or from double to float, except
337 // where the source is a constant expression and the actual value after
338 // conversion is within the range of values that can be represented (even
339 // if it cannot be represented exactly), or
340 case ICK_Floating_Conversion:
341 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
342 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
343 // FromType is larger than ToType.
344 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
345 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
346 // Constant!
347 assert(ConstantValue.isFloat());
348 llvm::APFloat FloatVal = ConstantValue.getFloat();
349 // Convert the source value into the target type.
350 bool ignored;
351 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
352 Ctx.getFloatTypeSemantics(ToType),
353 llvm::APFloat::rmNearestTiesToEven, &ignored);
354 // If there was no overflow, the source value is within the range of
355 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000356 if (ConvertStatus & llvm::APFloat::opOverflow) {
357 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000358 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000359 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000360 } else {
361 return NK_Variable_Narrowing;
362 }
363 }
364 return NK_Not_Narrowing;
365
366 // -- from an integer type or unscoped enumeration type to an integer type
367 // that cannot represent all the values of the original type, except where
368 // the source is a constant expression and the actual value after
369 // conversion will fit into the target type and will produce the original
370 // value when converted back to the original type.
Richard Smith64ecacf2015-02-19 00:39:05 +0000371 case ICK_Integral_Conversion:
372 IntegralConversion: {
Richard Smith66e05fe2012-01-18 05:21:49 +0000373 assert(FromType->isIntegralOrUnscopedEnumerationType());
374 assert(ToType->isIntegralOrUnscopedEnumerationType());
375 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
376 const unsigned FromWidth = Ctx.getIntWidth(FromType);
377 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
378 const unsigned ToWidth = Ctx.getIntWidth(ToType);
379
380 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000381 (FromWidth == ToWidth && FromSigned != ToSigned) ||
382 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000383 // Not all values of FromType can be represented in ToType.
384 llvm::APSInt InitializerValue;
385 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith25a80d42012-06-13 01:07:41 +0000386 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
387 // Such conversions on variables are always narrowing.
388 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000389 }
390 bool Narrowing = false;
391 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000392 // Negative -> unsigned is narrowing. Otherwise, more bits is never
393 // narrowing.
394 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000395 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000396 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000397 // Add a bit to the InitializerValue so we don't have to worry about
398 // signed vs. unsigned comparisons.
399 InitializerValue = InitializerValue.extend(
400 InitializerValue.getBitWidth() + 1);
401 // Convert the initializer to and from the target width and signed-ness.
402 llvm::APSInt ConvertedValue = InitializerValue;
403 ConvertedValue = ConvertedValue.trunc(ToWidth);
404 ConvertedValue.setIsSigned(ToSigned);
405 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
406 ConvertedValue.setIsSigned(InitializerValue.isSigned());
407 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000408 if (ConvertedValue != InitializerValue)
409 Narrowing = true;
410 }
411 if (Narrowing) {
412 ConstantType = Initializer->getType();
413 ConstantValue = APValue(InitializerValue);
414 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000415 }
416 }
417 return NK_Not_Narrowing;
418 }
419
420 default:
421 // Other kinds of conversions are not narrowings.
422 return NK_Not_Narrowing;
423 }
424}
425
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000426/// dump - Print this standard conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000427/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000428void StandardConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000429 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000430 bool PrintedSomething = false;
431 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000432 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000433 PrintedSomething = true;
434 }
435
436 if (Second != ICK_Identity) {
437 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000438 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000439 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000440 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000441
442 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000443 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000444 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000445 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000446 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000447 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000448 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000449 PrintedSomething = true;
450 }
451
452 if (Third != ICK_Identity) {
453 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000454 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000455 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000456 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000457 PrintedSomething = true;
458 }
459
460 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000461 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000462 }
463}
464
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000465/// dump - Print this user-defined conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000466/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000467void UserDefinedConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000468 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000469 if (Before.First || Before.Second || Before.Third) {
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000470 Before.dump();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000471 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000472 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000473 if (ConversionFunction)
474 OS << '\'' << *ConversionFunction << '\'';
475 else
476 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000477 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000478 OS << " -> ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000479 After.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000480 }
481}
482
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000483/// dump - Print this implicit conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000484/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000485void ImplicitConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000486 raw_ostream &OS = llvm::errs();
Richard Smitha93f1022013-09-06 22:30:28 +0000487 if (isStdInitializerListElement())
488 OS << "Worst std::initializer_list element conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000489 switch (ConversionKind) {
490 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000491 OS << "Standard conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000492 Standard.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000493 break;
494 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000495 OS << "User-defined conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000496 UserDefined.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000497 break;
498 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000499 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000500 break;
John McCall0d1da222010-01-12 00:44:57 +0000501 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000502 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000503 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000504 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000505 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000506 break;
507 }
508
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000509 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000510}
511
John McCall0d1da222010-01-12 00:44:57 +0000512void AmbiguousConversionSequence::construct() {
513 new (&conversions()) ConversionSet();
514}
515
516void AmbiguousConversionSequence::destruct() {
517 conversions().~ConversionSet();
518}
519
520void
521AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
522 FromTypePtr = O.FromTypePtr;
523 ToTypePtr = O.ToTypePtr;
524 new (&conversions()) ConversionSet(O.conversions());
525}
526
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000527namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000528 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000529 // template argument information.
530 struct DFIArguments {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000531 TemplateArgument FirstArg;
532 TemplateArgument SecondArg;
533 };
Larisse Voufo98b20f12013-07-19 23:00:19 +0000534 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000535 // template parameter and template argument information.
536 struct DFIParamWithArguments : DFIArguments {
537 TemplateParameter Param;
538 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000539}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000540
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000541/// \brief Convert from Sema's representation of template deduction information
542/// to the form used in overload-candidate information.
Richard Smith17c00b42014-11-12 01:24:00 +0000543DeductionFailureInfo
544clang::MakeDeductionFailureInfo(ASTContext &Context,
545 Sema::TemplateDeductionResult TDK,
546 TemplateDeductionInfo &Info) {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000547 DeductionFailureInfo Result;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000548 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000549 Result.HasDiagnostic = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000550 Result.Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000551 switch (TDK) {
552 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000553 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000554 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000555 case Sema::TDK_TooManyArguments:
556 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000557 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000558
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000559 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000560 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000561 Result.Data = Info.Param.getOpaqueValue();
562 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000563
Richard Smith44ecdbd2013-01-31 05:19:49 +0000564 case Sema::TDK_NonDeducedMismatch: {
565 // FIXME: Should allocate from normal heap so that we can free this later.
566 DFIArguments *Saved = new (Context) DFIArguments;
567 Saved->FirstArg = Info.FirstArg;
568 Saved->SecondArg = Info.SecondArg;
569 Result.Data = Saved;
570 break;
571 }
572
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000573 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000574 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000575 // FIXME: Should allocate from normal heap so that we can free this later.
576 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000577 Saved->Param = Info.Param;
578 Saved->FirstArg = Info.FirstArg;
579 Saved->SecondArg = Info.SecondArg;
580 Result.Data = Saved;
581 break;
582 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000583
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000584 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000585 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000586 if (Info.hasSFINAEDiagnostic()) {
587 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
588 SourceLocation(), PartialDiagnostic::NullDiagnostic());
589 Info.takeSFINAEDiagnostic(*Diag);
590 Result.HasDiagnostic = true;
591 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000592 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000593
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000594 case Sema::TDK_FailedOverloadResolution:
Richard Smith8c6eeb92013-01-31 04:03:12 +0000595 Result.Data = Info.Expression;
596 break;
597
Richard Smith44ecdbd2013-01-31 05:19:49 +0000598 case Sema::TDK_MiscellaneousDeductionFailure:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000599 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000600 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000601
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000602 return Result;
603}
John McCall0d1da222010-01-12 00:44:57 +0000604
Larisse Voufo98b20f12013-07-19 23:00:19 +0000605void DeductionFailureInfo::Destroy() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000606 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
607 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000608 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000609 case Sema::TDK_InstantiationDepth:
610 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000611 case Sema::TDK_TooManyArguments:
612 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000613 case Sema::TDK_InvalidExplicitArguments:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000614 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000615 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000616
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000617 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000618 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000619 case Sema::TDK_NonDeducedMismatch:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000620 // FIXME: Destroy the data?
Craig Topperc3ec1492014-05-26 06:22:03 +0000621 Data = nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000622 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000623
624 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000625 // FIXME: Destroy the template argument list?
Craig Topperc3ec1492014-05-26 06:22:03 +0000626 Data = nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000627 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
628 Diag->~PartialDiagnosticAt();
629 HasDiagnostic = false;
630 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000631 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000632
Douglas Gregor461761d2010-05-08 18:20:53 +0000633 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000634 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000635 break;
636 }
637}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000638
Larisse Voufo98b20f12013-07-19 23:00:19 +0000639PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smith9ca64612012-05-07 09:03:25 +0000640 if (HasDiagnostic)
641 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
Craig Topperc3ec1492014-05-26 06:22:03 +0000642 return nullptr;
Richard Smith9ca64612012-05-07 09:03:25 +0000643}
644
Larisse Voufo98b20f12013-07-19 23:00:19 +0000645TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000646 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
647 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000648 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000649 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000650 case Sema::TDK_TooManyArguments:
651 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000652 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000653 case Sema::TDK_NonDeducedMismatch:
654 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000655 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000656
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000657 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000658 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000659 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000660
661 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000662 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000663 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000664
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000665 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000666 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000667 break;
668 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000669
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000670 return TemplateParameter();
671}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000672
Larisse Voufo98b20f12013-07-19 23:00:19 +0000673TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregord09efd42010-05-08 20:07:26 +0000674 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith44ecdbd2013-01-31 05:19:49 +0000675 case Sema::TDK_Success:
676 case Sema::TDK_Invalid:
677 case Sema::TDK_InstantiationDepth:
678 case Sema::TDK_TooManyArguments:
679 case Sema::TDK_TooFewArguments:
680 case Sema::TDK_Incomplete:
681 case Sema::TDK_InvalidExplicitArguments:
682 case Sema::TDK_Inconsistent:
683 case Sema::TDK_Underqualified:
684 case Sema::TDK_NonDeducedMismatch:
685 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000686 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000687
Richard Smith44ecdbd2013-01-31 05:19:49 +0000688 case Sema::TDK_SubstitutionFailure:
689 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000690
Richard Smith44ecdbd2013-01-31 05:19:49 +0000691 // Unhandled
692 case Sema::TDK_MiscellaneousDeductionFailure:
693 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000694 }
695
Craig Topperc3ec1492014-05-26 06:22:03 +0000696 return nullptr;
Douglas Gregord09efd42010-05-08 20:07:26 +0000697}
698
Larisse Voufo98b20f12013-07-19 23:00:19 +0000699const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000700 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
701 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000702 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000703 case Sema::TDK_InstantiationDepth:
704 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000705 case Sema::TDK_TooManyArguments:
706 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000707 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000708 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000709 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000710 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000711
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000712 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000713 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000714 case Sema::TDK_NonDeducedMismatch:
715 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000716
Douglas Gregor461761d2010-05-08 18:20:53 +0000717 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000718 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000719 break;
720 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000721
Craig Topperc3ec1492014-05-26 06:22:03 +0000722 return nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000723}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000724
Larisse Voufo98b20f12013-07-19 23:00:19 +0000725const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000726 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
727 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000728 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000729 case Sema::TDK_InstantiationDepth:
730 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000731 case Sema::TDK_TooManyArguments:
732 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000733 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000734 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000735 case Sema::TDK_FailedOverloadResolution:
Craig Topperc3ec1492014-05-26 06:22:03 +0000736 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000737
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000738 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000739 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000740 case Sema::TDK_NonDeducedMismatch:
741 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000742
Douglas Gregor461761d2010-05-08 18:20:53 +0000743 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000744 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000745 break;
746 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000747
Craig Topperc3ec1492014-05-26 06:22:03 +0000748 return nullptr;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000749}
750
Larisse Voufo98b20f12013-07-19 23:00:19 +0000751Expr *DeductionFailureInfo::getExpr() {
Richard Smith8c6eeb92013-01-31 04:03:12 +0000752 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
753 Sema::TDK_FailedOverloadResolution)
754 return static_cast<Expr*>(Data);
755
Craig Topperc3ec1492014-05-26 06:22:03 +0000756 return nullptr;
Richard Smith8c6eeb92013-01-31 04:03:12 +0000757}
758
Benjamin Kramer97e59492012-10-09 15:52:25 +0000759void OverloadCandidateSet::destroyCandidates() {
Richard Smith0bf93aa2012-07-18 23:52:59 +0000760 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer02b08432012-01-14 20:16:52 +0000761 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
762 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smith0bf93aa2012-07-18 23:52:59 +0000763 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
764 i->DeductionFailure.Destroy();
765 }
Benjamin Kramer97e59492012-10-09 15:52:25 +0000766}
767
768void OverloadCandidateSet::clear() {
769 destroyCandidates();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000770 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000771 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000772 Functions.clear();
773}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000774
John McCall4124c492011-10-17 18:40:02 +0000775namespace {
776 class UnbridgedCastsSet {
777 struct Entry {
778 Expr **Addr;
779 Expr *Saved;
780 };
781 SmallVector<Entry, 2> Entries;
782
783 public:
784 void save(Sema &S, Expr *&E) {
785 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
786 Entry entry = { &E, E };
787 Entries.push_back(entry);
788 E = S.stripARCUnbridgedCast(E);
789 }
790
791 void restore() {
792 for (SmallVectorImpl<Entry>::iterator
793 i = Entries.begin(), e = Entries.end(); i != e; ++i)
794 *i->Addr = i->Saved;
795 }
796 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000797}
John McCall4124c492011-10-17 18:40:02 +0000798
799/// checkPlaceholderForOverload - Do any interesting placeholder-like
800/// preprocessing on the given expression.
801///
802/// \param unbridgedCasts a collection to which to add unbridged casts;
803/// without this, they will be immediately diagnosed as errors
804///
805/// Return true on unrecoverable error.
Craig Topperc3ec1492014-05-26 06:22:03 +0000806static bool
807checkPlaceholderForOverload(Sema &S, Expr *&E,
808 UnbridgedCastsSet *unbridgedCasts = nullptr) {
John McCall4124c492011-10-17 18:40:02 +0000809 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
810 // We can't handle overloaded expressions here because overload
811 // resolution might reasonably tweak them.
812 if (placeholder->getKind() == BuiltinType::Overload) return false;
813
814 // If the context potentially accepts unbridged ARC casts, strip
815 // the unbridged cast and add it to the collection for later restoration.
816 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
817 unbridgedCasts) {
818 unbridgedCasts->save(S, E);
819 return false;
820 }
821
822 // Go ahead and check everything else.
823 ExprResult result = S.CheckPlaceholderExpr(E);
824 if (result.isInvalid())
825 return true;
826
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000827 E = result.get();
John McCall4124c492011-10-17 18:40:02 +0000828 return false;
829 }
830
831 // Nothing to do.
832 return false;
833}
834
835/// checkArgPlaceholdersForOverload - Check a set of call operands for
836/// placeholders.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000837static bool checkArgPlaceholdersForOverload(Sema &S,
838 MultiExprArg Args,
John McCall4124c492011-10-17 18:40:02 +0000839 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000840 for (unsigned i = 0, e = Args.size(); i != e; ++i)
841 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall4124c492011-10-17 18:40:02 +0000842 return true;
843
844 return false;
845}
846
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000847// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000848// overload of the declarations in Old. This routine returns false if
849// New and Old cannot be overloaded, e.g., if New has the same
850// signature as some function in Old (C++ 1.3.10) or if the Old
851// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000852// it does return false, MatchedDecl will point to the decl that New
853// cannot be overloaded with. This decl may be a UsingShadowDecl on
854// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000855//
856// Example: Given the following input:
857//
858// void f(int, float); // #1
859// void f(int, int); // #2
860// int f(int, int); // #3
861//
862// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000863// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000864//
John McCall3d988d92009-12-02 08:47:38 +0000865// When we process #2, Old contains only the FunctionDecl for #1. By
866// comparing the parameter types, we see that #1 and #2 are overloaded
867// (since they have different signatures), so this routine returns
868// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000869//
John McCall3d988d92009-12-02 08:47:38 +0000870// When we process #3, Old is an overload set containing #1 and #2. We
871// compare the signatures of #3 to #1 (they're overloaded, so we do
872// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
873// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000874// signature), IsOverload returns false and MatchedDecl will be set to
875// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000876//
877// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
878// into a class by a using declaration. The rules for whether to hide
879// shadow declarations ignore some properties which otherwise figure
880// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000881Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000882Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
883 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000884 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000885 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000886 NamedDecl *OldD = *I;
887
888 bool OldIsUsingDecl = false;
889 if (isa<UsingShadowDecl>(OldD)) {
890 OldIsUsingDecl = true;
891
892 // We can always introduce two using declarations into the same
893 // context, even if they have identical signatures.
894 if (NewIsUsingDecl) continue;
895
896 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
897 }
898
899 // If either declaration was introduced by a using declaration,
900 // we'll need to use slightly different rules for matching.
901 // Essentially, these rules are the normal rules, except that
902 // function templates hide function templates with different
903 // return types or template parameter lists.
904 bool UseMemberUsingDeclRules =
John McCallc70fca62013-04-03 21:19:47 +0000905 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
906 !New->getFriendObjectKind();
John McCalle9cccd82010-06-16 08:42:20 +0000907
Alp Tokera2794f92014-01-22 07:29:52 +0000908 if (FunctionDecl *OldF = OldD->getAsFunction()) {
John McCalle9cccd82010-06-16 08:42:20 +0000909 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
910 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
911 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
912 continue;
913 }
914
Alp Tokera2794f92014-01-22 07:29:52 +0000915 if (!isa<FunctionTemplateDecl>(OldD) &&
916 !shouldLinkPossiblyHiddenDecl(*I, New))
Rafael Espindola5bddd6a2013-04-15 12:49:13 +0000917 continue;
918
John McCalldaa3d6b2009-12-09 03:35:25 +0000919 Match = *I;
920 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000921 }
John McCalla8987a2942010-11-10 03:01:53 +0000922 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000923 // We can overload with these, which can show up when doing
924 // redeclaration checks for UsingDecls.
925 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000926 } else if (isa<TagDecl>(OldD)) {
927 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000928 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
929 // Optimistically assume that an unresolved using decl will
930 // overload; if it doesn't, we'll have to diagnose during
931 // template instantiation.
932 } else {
John McCall1f82f242009-11-18 22:49:29 +0000933 // (C++ 13p1):
934 // Only function declarations can be overloaded; object and type
935 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000936 Match = *I;
937 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000938 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000939 }
John McCall1f82f242009-11-18 22:49:29 +0000940
John McCalldaa3d6b2009-12-09 03:35:25 +0000941 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000942}
943
Richard Smithac974a32013-06-30 09:48:50 +0000944bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
945 bool UseUsingDeclRules) {
946 // C++ [basic.start.main]p2: This function shall not be overloaded.
947 if (New->isMain())
Rafael Espindola576127d2012-12-28 14:21:58 +0000948 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +0000949
David Majnemerc729b0b2013-09-16 22:44:20 +0000950 // MSVCRT user defined entry points cannot be overloaded.
951 if (New->isMSVCRTEntryPoint())
952 return false;
953
John McCall1f82f242009-11-18 22:49:29 +0000954 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
955 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
956
957 // C++ [temp.fct]p2:
958 // A function template can be overloaded with other function templates
959 // and with normal (non-template) functions.
Craig Topperc3ec1492014-05-26 06:22:03 +0000960 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
John McCall1f82f242009-11-18 22:49:29 +0000961 return true;
962
963 // Is the function New an overload of the function Old?
Richard Smithac974a32013-06-30 09:48:50 +0000964 QualType OldQType = Context.getCanonicalType(Old->getType());
965 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall1f82f242009-11-18 22:49:29 +0000966
967 // Compare the signatures (C++ 1.3.10) of the two functions to
968 // determine whether they are overloads. If we find any mismatch
969 // in the signature, they are overloads.
970
971 // If either of these functions is a K&R-style function (no
972 // prototype), then we consider them to have matching signatures.
973 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
974 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
975 return false;
976
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000977 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
978 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000979
980 // The signature of a function includes the types of its
981 // parameters (C++ 1.3.10), which includes the presence or absence
982 // of the ellipsis; see C++ DR 357).
983 if (OldQType != NewQType &&
Alp Toker9cacbab2014-01-20 20:26:09 +0000984 (OldType->getNumParams() != NewType->getNumParams() ||
John McCall1f82f242009-11-18 22:49:29 +0000985 OldType->isVariadic() != NewType->isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +0000986 !FunctionParamTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000987 return true;
988
989 // C++ [temp.over.link]p4:
990 // The signature of a function template consists of its function
991 // signature, its return type and its template parameter list. The names
992 // of the template parameters are significant only for establishing the
993 // relationship between the template parameters and the rest of the
994 // signature.
995 //
996 // We check the return type and template parameter lists for function
997 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000998 //
999 // However, we don't consider either of these when deciding whether
1000 // a member introduced by a shadow declaration is hidden.
1001 if (!UseUsingDeclRules && NewTemplate &&
Richard Smithac974a32013-06-30 09:48:50 +00001002 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1003 OldTemplate->getTemplateParameters(),
1004 false, TPL_TemplateMatch) ||
Alp Toker314cc812014-01-25 16:55:45 +00001005 OldType->getReturnType() != NewType->getReturnType()))
John McCall1f82f242009-11-18 22:49:29 +00001006 return true;
1007
1008 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001009 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001010 //
1011 // As part of this, also check whether one of the member functions
1012 // is static, in which case they are not overloads (C++
1013 // 13.1p2). While not part of the definition of the signature,
1014 // this check is important to determine whether these functions
1015 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001016 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1017 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001018 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001019 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1020 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1021 if (!UseUsingDeclRules &&
1022 (OldMethod->getRefQualifier() == RQ_None ||
1023 NewMethod->getRefQualifier() == RQ_None)) {
1024 // C++0x [over.load]p2:
1025 // - Member function declarations with the same name and the same
1026 // parameter-type-list as well as member function template
1027 // declarations with the same name, the same parameter-type-list, and
1028 // the same template parameter lists cannot be overloaded if any of
1029 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001030 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001031 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001032 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001033 }
1034 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001035 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001036
Richard Smith574f4f62013-01-14 05:37:29 +00001037 // We may not have applied the implicit const for a constexpr member
1038 // function yet (because we haven't yet resolved whether this is a static
1039 // or non-static member function). Add it now, on the assumption that this
1040 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001041 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001042 unsigned NewQuals = NewMethod->getTypeQualifiers();
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001043 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001044 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001045 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001046
1047 // We do not allow overloading based off of '__restrict'.
1048 OldQuals &= ~Qualifiers::Restrict;
1049 NewQuals &= ~Qualifiers::Restrict;
1050 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001051 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001052 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001053
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001054 // enable_if attributes are an order-sensitive part of the signature.
1055 for (specific_attr_iterator<EnableIfAttr>
1056 NewI = New->specific_attr_begin<EnableIfAttr>(),
1057 NewE = New->specific_attr_end<EnableIfAttr>(),
1058 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1059 OldE = Old->specific_attr_end<EnableIfAttr>();
1060 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1061 if (NewI == NewE || OldI == OldE)
1062 return true;
1063 llvm::FoldingSetNodeID NewID, OldID;
1064 NewI->getCond()->Profile(NewID, Context, true);
1065 OldI->getCond()->Profile(OldID, Context, true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00001066 if (NewID != OldID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001067 return true;
1068 }
1069
John McCall1f82f242009-11-18 22:49:29 +00001070 // The signatures match; this is not an overload.
1071 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001072}
1073
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001074/// \brief Checks availability of the function depending on the current
1075/// function context. Inside an unavailable function, unavailability is ignored.
1076///
1077/// \returns true if \arg FD is unavailable and current context is inside
1078/// an available function, false otherwise.
1079bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1080 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1081}
1082
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001083/// \brief Tries a user-defined conversion from From to ToType.
1084///
1085/// Produces an implicit conversion sequence for when a standard conversion
1086/// is not an option. See TryImplicitConversion for more information.
1087static ImplicitConversionSequence
1088TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1089 bool SuppressUserConversions,
1090 bool AllowExplicit,
1091 bool InOverloadResolution,
1092 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001093 bool AllowObjCWritebackConversion,
1094 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001095 ImplicitConversionSequence ICS;
1096
1097 if (SuppressUserConversions) {
1098 // We're not in the case above, so there is no conversion that
1099 // we can perform.
1100 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1101 return ICS;
1102 }
1103
1104 // Attempt user-defined conversion.
Richard Smith100b24a2014-04-17 01:52:14 +00001105 OverloadCandidateSet Conversions(From->getExprLoc(),
1106 OverloadCandidateSet::CSK_Normal);
Richard Smith48372b62015-01-27 03:30:40 +00001107 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1108 Conversions, AllowExplicit,
1109 AllowObjCConversionOnExplicit)) {
1110 case OR_Success:
1111 case OR_Deleted:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001112 ICS.setUserDefined();
Ismail Pazarbasidf1a2802014-01-24 13:16:17 +00001113 ICS.UserDefined.Before.setAsIdentityConversion();
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001114 // C++ [over.ics.user]p4:
1115 // A conversion of an expression of class type to the same class
1116 // type is given Exact Match rank, and a conversion of an
1117 // expression of class type to a base class of that type is
1118 // given Conversion rank, in spite of the fact that a copy
1119 // constructor (i.e., a user-defined conversion function) is
1120 // called for those cases.
1121 if (CXXConstructorDecl *Constructor
1122 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1123 QualType FromCanon
1124 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1125 QualType ToCanon
1126 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1127 if (Constructor->isCopyConstructor() &&
1128 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1129 // Turn this into a "standard" conversion sequence, so that it
1130 // gets ranked with standard conversion sequences.
1131 ICS.setStandard();
1132 ICS.Standard.setAsIdentityConversion();
1133 ICS.Standard.setFromType(From->getType());
1134 ICS.Standard.setAllToTypes(ToType);
1135 ICS.Standard.CopyConstructor = Constructor;
1136 if (ToCanon != FromCanon)
1137 ICS.Standard.Second = ICK_Derived_To_Base;
1138 }
1139 }
Richard Smith48372b62015-01-27 03:30:40 +00001140 break;
1141
1142 case OR_Ambiguous:
Richard Smith1bbaba82015-01-27 23:23:39 +00001143 ICS.setAmbiguous();
1144 ICS.Ambiguous.setFromType(From->getType());
1145 ICS.Ambiguous.setToType(ToType);
1146 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1147 Cand != Conversions.end(); ++Cand)
1148 if (Cand->Viable)
1149 ICS.Ambiguous.addConversion(Cand->Function);
1150 break;
Richard Smith48372b62015-01-27 03:30:40 +00001151
1152 // Fall through.
1153 case OR_No_Viable_Function:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001154 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Richard Smith48372b62015-01-27 03:30:40 +00001155 break;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001156 }
1157
1158 return ICS;
1159}
1160
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001161/// TryImplicitConversion - Attempt to perform an implicit conversion
1162/// from the given expression (Expr) to the given type (ToType). This
1163/// function returns an implicit conversion sequence that can be used
1164/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001165///
1166/// void f(float f);
1167/// void g(int i) { f(i); }
1168///
1169/// this routine would produce an implicit conversion sequence to
1170/// describe the initialization of f from i, which will be a standard
1171/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1172/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1173//
1174/// Note that this routine only determines how the conversion can be
1175/// performed; it does not actually perform the conversion. As such,
1176/// it will not produce any diagnostics if no conversion is available,
1177/// but will instead return an implicit conversion sequence of kind
1178/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001179///
1180/// If @p SuppressUserConversions, then user-defined conversions are
1181/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001182/// If @p AllowExplicit, then explicit user-defined conversions are
1183/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001184///
1185/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1186/// writeback conversion, which allows __autoreleasing id* parameters to
1187/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001188static ImplicitConversionSequence
1189TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1190 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001191 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001192 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001193 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001194 bool AllowObjCWritebackConversion,
1195 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001196 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001197 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001198 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001199 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001200 return ICS;
1201 }
1202
David Blaikiebbafb8a2012-03-11 07:00:24 +00001203 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001204 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001205 return ICS;
1206 }
1207
Douglas Gregor836a7e82010-08-11 02:15:33 +00001208 // C++ [over.ics.user]p4:
1209 // A conversion of an expression of class type to the same class
1210 // type is given Exact Match rank, and a conversion of an
1211 // expression of class type to a base class of that type is
1212 // given Conversion rank, in spite of the fact that a copy/move
1213 // constructor (i.e., a user-defined conversion function) is
1214 // called for those cases.
1215 QualType FromType = From->getType();
1216 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001217 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1218 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001219 ICS.setStandard();
1220 ICS.Standard.setAsIdentityConversion();
1221 ICS.Standard.setFromType(FromType);
1222 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001223
Douglas Gregor5ab11652010-04-17 22:01:05 +00001224 // We don't actually check at this point whether there is a valid
1225 // copy/move constructor, since overloading just assumes that it
1226 // exists. When we actually perform initialization, we'll find the
1227 // appropriate constructor to copy the returned object, if needed.
Craig Topperc3ec1492014-05-26 06:22:03 +00001228 ICS.Standard.CopyConstructor = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001229
Douglas Gregor5ab11652010-04-17 22:01:05 +00001230 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001231 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001232 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001233
Douglas Gregor836a7e82010-08-11 02:15:33 +00001234 return ICS;
1235 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001236
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001237 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1238 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001239 AllowObjCWritebackConversion,
1240 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001241}
1242
John McCall31168b02011-06-15 23:02:42 +00001243ImplicitConversionSequence
1244Sema::TryImplicitConversion(Expr *From, QualType ToType,
1245 bool SuppressUserConversions,
1246 bool AllowExplicit,
1247 bool InOverloadResolution,
1248 bool CStyle,
1249 bool AllowObjCWritebackConversion) {
Richard Smith17c00b42014-11-12 01:24:00 +00001250 return ::TryImplicitConversion(*this, From, ToType,
1251 SuppressUserConversions, AllowExplicit,
1252 InOverloadResolution, CStyle,
1253 AllowObjCWritebackConversion,
1254 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001255}
1256
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001257/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001258/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001259/// converted expression. Flavor is the kind of conversion we're
1260/// performing, used in the error message. If @p AllowExplicit,
1261/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001262ExprResult
1263Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001264 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001265 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001266 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001267}
1268
John Wiegley01296292011-04-08 18:41:53 +00001269ExprResult
1270Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001271 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001272 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001273 if (checkPlaceholderForOverload(*this, From))
1274 return ExprError();
1275
John McCall31168b02011-06-15 23:02:42 +00001276 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1277 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001278 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001279 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001280 if (getLangOpts().ObjC1)
1281 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1282 ToType, From->getType(), From);
Richard Smith17c00b42014-11-12 01:24:00 +00001283 ICS = ::TryImplicitConversion(*this, From, ToType,
1284 /*SuppressUserConversions=*/false,
1285 AllowExplicit,
1286 /*InOverloadResolution=*/false,
1287 /*CStyle=*/false,
1288 AllowObjCWritebackConversion,
1289 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001290 return PerformImplicitConversion(From, ToType, ICS, Action);
1291}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001292
1293/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001294/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001295bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1296 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001297 if (Context.hasSameUnqualifiedType(FromType, ToType))
1298 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001299
John McCall991eb4b2010-12-21 00:44:39 +00001300 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1301 // where F adds one of the following at most once:
1302 // - a pointer
1303 // - a member pointer
1304 // - a block pointer
1305 CanQualType CanTo = Context.getCanonicalType(ToType);
1306 CanQualType CanFrom = Context.getCanonicalType(FromType);
1307 Type::TypeClass TyClass = CanTo->getTypeClass();
1308 if (TyClass != CanFrom->getTypeClass()) return false;
1309 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1310 if (TyClass == Type::Pointer) {
1311 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1312 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1313 } else if (TyClass == Type::BlockPointer) {
1314 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1315 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1316 } else if (TyClass == Type::MemberPointer) {
1317 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1318 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1319 } else {
1320 return false;
1321 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001322
John McCall991eb4b2010-12-21 00:44:39 +00001323 TyClass = CanTo->getTypeClass();
1324 if (TyClass != CanFrom->getTypeClass()) return false;
1325 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1326 return false;
1327 }
1328
1329 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1330 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1331 if (!EInfo.getNoReturn()) return false;
1332
1333 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1334 assert(QualType(FromFn, 0).isCanonical());
1335 if (QualType(FromFn, 0) != CanTo) return false;
1336
1337 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001338 return true;
1339}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001340
Douglas Gregor46188682010-05-18 22:42:18 +00001341/// \brief Determine whether the conversion from FromType to ToType is a valid
1342/// vector conversion.
1343///
1344/// \param ICK Will be set to the vector conversion kind, if this is a vector
1345/// conversion.
John McCall9b595db2014-02-04 23:58:19 +00001346static bool IsVectorConversion(Sema &S, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001347 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001348 // We need at least one of these types to be a vector type to have a vector
1349 // conversion.
1350 if (!ToType->isVectorType() && !FromType->isVectorType())
1351 return false;
1352
1353 // Identical types require no conversions.
John McCall9b595db2014-02-04 23:58:19 +00001354 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor46188682010-05-18 22:42:18 +00001355 return false;
1356
1357 // There are no conversions between extended vector types, only identity.
1358 if (ToType->isExtVectorType()) {
1359 // There are no conversions between extended vector types other than the
1360 // identity conversion.
1361 if (FromType->isExtVectorType())
1362 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001363
Douglas Gregor46188682010-05-18 22:42:18 +00001364 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001365 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001366 ICK = ICK_Vector_Splat;
1367 return true;
1368 }
1369 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001370
1371 // We can perform the conversion between vector types in the following cases:
1372 // 1)vector types are equivalent AltiVec and GCC vector types
1373 // 2)lax vector conversions are permitted and the vector types are of the
1374 // same size
1375 if (ToType->isVectorType() && FromType->isVectorType()) {
John McCall9b595db2014-02-04 23:58:19 +00001376 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1377 S.isLaxVectorConversion(FromType, ToType)) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001378 ICK = ICK_Vector_Conversion;
1379 return true;
1380 }
Douglas Gregor46188682010-05-18 22:42:18 +00001381 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001382
Douglas Gregor46188682010-05-18 22:42:18 +00001383 return false;
1384}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001385
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001386static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1387 bool InOverloadResolution,
1388 StandardConversionSequence &SCS,
1389 bool CStyle);
Douglas Gregorc79862f2012-04-12 17:51:55 +00001390
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001391/// IsStandardConversion - Determines whether there is a standard
1392/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1393/// expression From to the type ToType. Standard conversion sequences
1394/// only consider non-class types; for conversions that involve class
1395/// types, use TryImplicitConversion. If a conversion exists, SCS will
1396/// contain the standard conversion sequence required to perform this
1397/// conversion and this routine will return true. Otherwise, this
1398/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001399static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1400 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001401 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001402 bool CStyle,
1403 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001404 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001405
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001406 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001407 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001408 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001409 SCS.setFromType(FromType);
Craig Topperc3ec1492014-05-26 06:22:03 +00001410 SCS.CopyConstructor = nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001411
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001412 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001413 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001414 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001415 if (S.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001416 return false;
1417
Mike Stump11289f42009-09-09 15:08:12 +00001418 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001419 }
1420
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001421 // The first conversion can be an lvalue-to-rvalue conversion,
1422 // array-to-pointer conversion, or function-to-pointer conversion
1423 // (C++ 4p1).
1424
John McCall5c32be02010-08-24 20:38:10 +00001425 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001426 DeclAccessPair AccessPair;
1427 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001428 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001429 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001430 // We were able to resolve the address of the overloaded function,
1431 // so we can convert to the type of that function.
1432 FromType = Fn->getType();
Ehsan Akhgaric3ad3ba2014-07-22 20:20:14 +00001433 SCS.setFromType(FromType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001434
1435 // we can sometimes resolve &foo<int> regardless of ToType, so check
1436 // if the type matches (identity) or we are converting to bool
1437 if (!S.Context.hasSameUnqualifiedType(
1438 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1439 QualType resultTy;
1440 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001441 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001442 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1443 // otherwise, only a boolean conversion is standard
1444 if (!ToType->isBooleanType())
1445 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001446 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001447
Chandler Carruthffce2452011-03-29 08:08:18 +00001448 // Check if the "from" expression is taking the address of an overloaded
1449 // function and recompute the FromType accordingly. Take advantage of the
1450 // fact that non-static member functions *must* have such an address-of
1451 // expression.
1452 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1453 if (Method && !Method->isStatic()) {
1454 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1455 "Non-unary operator on non-static member address");
1456 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1457 == UO_AddrOf &&
1458 "Non-address-of operator on non-static member address");
1459 const Type *ClassType
1460 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1461 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001462 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1463 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1464 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001465 "Non-address-of operator for overloaded function expression");
1466 FromType = S.Context.getPointerType(FromType);
1467 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001468
Douglas Gregor980fb162010-04-29 18:24:40 +00001469 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001470 assert(S.Context.hasSameType(
1471 FromType,
1472 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001473 } else {
1474 return false;
1475 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001476 }
John McCall154a2fd2011-08-30 00:57:29 +00001477 // Lvalue-to-rvalue conversion (C++11 4.1):
1478 // A glvalue (3.10) of a non-function, non-array type T can
1479 // be converted to a prvalue.
1480 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001481 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001482 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001483 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001484 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001485
Douglas Gregorc79862f2012-04-12 17:51:55 +00001486 // C11 6.3.2.1p2:
1487 // ... if the lvalue has atomic type, the value has the non-atomic version
1488 // of the type of the lvalue ...
1489 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1490 FromType = Atomic->getValueType();
1491
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001492 // If T is a non-class type, the type of the rvalue is the
1493 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001494 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1495 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001496 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001497 } else if (FromType->isArrayType()) {
1498 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001499 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001500
1501 // An lvalue or rvalue of type "array of N T" or "array of unknown
1502 // bound of T" can be converted to an rvalue of type "pointer to
1503 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001504 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001505
John McCall5c32be02010-08-24 20:38:10 +00001506 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001507 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001508 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001509
1510 // For the purpose of ranking in overload resolution
1511 // (13.3.3.1.1), this conversion is considered an
1512 // array-to-pointer conversion followed by a qualification
1513 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001514 SCS.Second = ICK_Identity;
1515 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001516 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001517 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001518 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001519 }
John McCall086a4642010-11-24 05:12:34 +00001520 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001521 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001522 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001523
1524 // An lvalue of function type T can be converted to an rvalue of
1525 // type "pointer to T." The result is a pointer to the
1526 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001527 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001528 } else {
1529 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001530 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001531 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001532 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001533
1534 // The second conversion can be an integral promotion, floating
1535 // point promotion, integral conversion, floating point conversion,
1536 // floating-integral conversion, pointer conversion,
1537 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001538 // For overloading in C, this can also be a "compatible-type"
1539 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001540 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001541 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001542 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001543 // The unqualified versions of the types are the same: there's no
1544 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001545 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001546 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001547 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001548 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001549 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001550 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001551 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001552 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001553 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001554 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001555 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001556 SCS.Second = ICK_Complex_Promotion;
1557 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001558 } else if (ToType->isBooleanType() &&
1559 (FromType->isArithmeticType() ||
1560 FromType->isAnyPointerType() ||
1561 FromType->isBlockPointerType() ||
1562 FromType->isMemberPointerType() ||
1563 FromType->isNullPtrType())) {
1564 // Boolean conversions (C++ 4.12).
1565 SCS.Second = ICK_Boolean_Conversion;
1566 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001567 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001568 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001569 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001570 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001571 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001572 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001573 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001574 SCS.Second = ICK_Complex_Conversion;
1575 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001576 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1577 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001578 // Complex-real conversions (C99 6.3.1.7)
1579 SCS.Second = ICK_Complex_Real;
1580 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001581 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001582 // Floating point conversions (C++ 4.8).
1583 SCS.Second = ICK_Floating_Conversion;
1584 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001585 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001586 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001587 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001588 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001589 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001590 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001591 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001592 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001593 SCS.Second = ICK_Block_Pointer_Conversion;
1594 } else if (AllowObjCWritebackConversion &&
1595 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1596 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001597 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1598 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001599 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001600 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001601 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001602 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001603 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001604 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001605 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001606 SCS.Second = ICK_Pointer_Member;
John McCall9b595db2014-02-04 23:58:19 +00001607 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001608 SCS.Second = SecondICK;
1609 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001610 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001611 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001612 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001613 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001614 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001615 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001616 // Treat a conversion that strips "noreturn" as an identity conversion.
1617 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001618 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1619 InOverloadResolution,
1620 SCS, CStyle)) {
1621 SCS.Second = ICK_TransparentUnionConversion;
1622 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001623 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1624 CStyle)) {
1625 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001626 // appropriately.
1627 return true;
Guy Benyei259f9f42013-02-07 16:05:33 +00001628 } else if (ToType->isEventT() &&
1629 From->isIntegerConstantExpr(S.getASTContext()) &&
1630 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1631 SCS.Second = ICK_Zero_Event_Conversion;
1632 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001633 } else {
1634 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001635 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001636 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001637 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001638
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001639 QualType CanonFrom;
1640 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001641 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001642 bool ObjCLifetimeConversion;
1643 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1644 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001645 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001646 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001647 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001648 CanonFrom = S.Context.getCanonicalType(FromType);
1649 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001650 } else {
1651 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001652 SCS.Third = ICK_Identity;
1653
Mike Stump11289f42009-09-09 15:08:12 +00001654 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001655 // [...] Any difference in top-level cv-qualification is
1656 // subsumed by the initialization itself and does not constitute
1657 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001658 CanonFrom = S.Context.getCanonicalType(FromType);
1659 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001660 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001661 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault7d36c012013-02-26 21:15:54 +00001662 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001663 FromType = ToType;
1664 CanonFrom = CanonTo;
1665 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001666 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001667 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001668
1669 // If we have not converted the argument type to the parameter type,
1670 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001671 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001672 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001673
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001674 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001675}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001676
1677static bool
1678IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1679 QualType &ToType,
1680 bool InOverloadResolution,
1681 StandardConversionSequence &SCS,
1682 bool CStyle) {
1683
1684 const RecordType *UT = ToType->getAsUnionType();
1685 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1686 return false;
1687 // The field to initialize within the transparent union.
1688 RecordDecl *UD = UT->getDecl();
1689 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001690 for (const auto *it : UD->fields()) {
John McCall31168b02011-06-15 23:02:42 +00001691 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1692 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001693 ToType = it->getType();
1694 return true;
1695 }
1696 }
1697 return false;
1698}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001699
1700/// IsIntegralPromotion - Determines whether the conversion from the
1701/// expression From (whose potentially-adjusted type is FromType) to
1702/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1703/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001704bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001705 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001706 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001707 if (!To) {
1708 return false;
1709 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001710
1711 // An rvalue of type char, signed char, unsigned char, short int, or
1712 // unsigned short int can be converted to an rvalue of type int if
1713 // int can represent all the values of the source type; otherwise,
1714 // the source rvalue can be converted to an rvalue of type unsigned
1715 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001716 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1717 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001718 if (// We can promote any signed, promotable integer type to an int
1719 (FromType->isSignedIntegerType() ||
1720 // We can promote any unsigned integer type whose size is
1721 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001722 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001723 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001724 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001725 }
1726
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001727 return To->getKind() == BuiltinType::UInt;
1728 }
1729
Richard Smithb9c5a602012-09-13 21:18:54 +00001730 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001731 // A prvalue of an unscoped enumeration type whose underlying type is not
1732 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1733 // following types that can represent all the values of the enumeration
1734 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1735 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001736 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001737 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001738 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001739 // with lowest integer conversion rank (4.13) greater than the rank of long
1740 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001741 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001742 // C++11 [conv.prom]p4:
1743 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1744 // can be converted to a prvalue of its underlying type. Moreover, if
1745 // integral promotion can be applied to its underlying type, a prvalue of an
1746 // unscoped enumeration type whose underlying type is fixed can also be
1747 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001748 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1749 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1750 // provided for a scoped enumeration.
1751 if (FromEnumType->getDecl()->isScoped())
1752 return false;
1753
Richard Smithb9c5a602012-09-13 21:18:54 +00001754 // We can perform an integral promotion to the underlying type of the enum,
Richard Smithac8c1752015-03-28 00:31:40 +00001755 // even if that's not the promoted type. Note that the check for promoting
1756 // the underlying type is based on the type alone, and does not consider
1757 // the bitfield-ness of the actual source expression.
Richard Smithb9c5a602012-09-13 21:18:54 +00001758 if (FromEnumType->getDecl()->isFixed()) {
1759 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1760 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
Richard Smithac8c1752015-03-28 00:31:40 +00001761 IsIntegralPromotion(nullptr, Underlying, ToType);
Richard Smithb9c5a602012-09-13 21:18:54 +00001762 }
1763
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001764 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001765 if (ToType->isIntegerType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001766 !RequireCompleteType(From->getLocStart(), FromType, 0))
Richard Smith88f4bba2015-03-26 00:16:07 +00001767 return Context.hasSameUnqualifiedType(
1768 ToType, FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001769 }
John McCall56774992009-12-09 09:09:27 +00001770
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001771 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001772 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1773 // to an rvalue a prvalue of the first of the following types that can
1774 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001775 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001776 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001777 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001778 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001779 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001780 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001781 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001782 // Determine whether the type we're converting from is signed or
1783 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001784 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001785 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001786
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001787 // The types we'll try to promote to, in the appropriate
1788 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001789 QualType PromoteTypes[6] = {
1790 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001791 Context.LongTy, Context.UnsignedLongTy ,
1792 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001793 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001794 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001795 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1796 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001797 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001798 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1799 // We found the type that we can promote to. If this is the
1800 // type we wanted, we have a promotion. Otherwise, no
1801 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001802 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001803 }
1804 }
1805 }
1806
1807 // An rvalue for an integral bit-field (9.6) can be converted to an
1808 // rvalue of type int if int can represent all the values of the
1809 // bit-field; otherwise, it can be converted to unsigned int if
1810 // unsigned int can represent all the values of the bit-field. If
1811 // the bit-field is larger yet, no integral promotion applies to
1812 // it. If the bit-field has an enumerated type, it is treated as any
1813 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001814 // FIXME: We should delay checking of bit-fields until we actually perform the
1815 // conversion.
Richard Smith88f4bba2015-03-26 00:16:07 +00001816 if (From) {
John McCalld25db7e2013-05-06 21:39:12 +00001817 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Richard Smith88f4bba2015-03-26 00:16:07 +00001818 llvm::APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001819 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001820 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
Richard Smith88f4bba2015-03-26 00:16:07 +00001821 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
Douglas Gregor71235ec2009-05-02 02:18:30 +00001822 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001823
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001824 // Are we promoting to an int from a bitfield that fits in an int?
1825 if (BitWidth < ToSize ||
1826 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1827 return To->getKind() == BuiltinType::Int;
1828 }
Mike Stump11289f42009-09-09 15:08:12 +00001829
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001830 // Are we promoting to an unsigned int from an unsigned bitfield
1831 // that fits into an unsigned int?
1832 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1833 return To->getKind() == BuiltinType::UInt;
1834 }
Mike Stump11289f42009-09-09 15:08:12 +00001835
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001836 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001837 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001838 }
Richard Smith88f4bba2015-03-26 00:16:07 +00001839 }
Mike Stump11289f42009-09-09 15:08:12 +00001840
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001841 // An rvalue of type bool can be converted to an rvalue of type int,
1842 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001843 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001844 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001845 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001846
1847 return false;
1848}
1849
1850/// IsFloatingPointPromotion - Determines whether the conversion from
1851/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1852/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001853bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001854 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1855 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001856 /// An rvalue of type float can be converted to an rvalue of type
1857 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001858 if (FromBuiltin->getKind() == BuiltinType::Float &&
1859 ToBuiltin->getKind() == BuiltinType::Double)
1860 return true;
1861
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001862 // C99 6.3.1.5p1:
1863 // When a float is promoted to double or long double, or a
1864 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00001865 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001866 (FromBuiltin->getKind() == BuiltinType::Float ||
1867 FromBuiltin->getKind() == BuiltinType::Double) &&
1868 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1869 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001870
1871 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00001872 if (!getLangOpts().NativeHalfType &&
1873 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001874 ToBuiltin->getKind() == BuiltinType::Float)
1875 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001876 }
1877
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001878 return false;
1879}
1880
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001881/// \brief Determine if a conversion is a complex promotion.
1882///
1883/// A complex promotion is defined as a complex -> complex conversion
1884/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001885/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001886bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001887 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001888 if (!FromComplex)
1889 return false;
1890
John McCall9dd450b2009-09-21 23:43:11 +00001891 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001892 if (!ToComplex)
1893 return false;
1894
1895 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001896 ToComplex->getElementType()) ||
Craig Topperc3ec1492014-05-26 06:22:03 +00001897 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001898 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001899}
1900
Douglas Gregor237f96c2008-11-26 23:31:11 +00001901/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1902/// the pointer type FromPtr to a pointer to type ToPointee, with the
1903/// same type qualifiers as FromPtr has on its pointee type. ToType,
1904/// if non-empty, will be a pointer to ToType that may or may not have
1905/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001906///
Mike Stump11289f42009-09-09 15:08:12 +00001907static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001908BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001909 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001910 ASTContext &Context,
1911 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001912 assert((FromPtr->getTypeClass() == Type::Pointer ||
1913 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1914 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001915
John McCall31168b02011-06-15 23:02:42 +00001916 /// Conversions to 'id' subsume cv-qualifier conversions.
1917 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001918 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001919
1920 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001921 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001922 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001923 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001924
John McCall31168b02011-06-15 23:02:42 +00001925 if (StripObjCLifetime)
1926 Quals.removeObjCLifetime();
1927
Mike Stump11289f42009-09-09 15:08:12 +00001928 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001929 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001930 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001931 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001932 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001933
1934 // Build a pointer to ToPointee. It has the right qualifiers
1935 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001936 if (isa<ObjCObjectPointerType>(ToType))
1937 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001938 return Context.getPointerType(ToPointee);
1939 }
1940
1941 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001942 QualType QualifiedCanonToPointee
1943 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001944
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001945 if (isa<ObjCObjectPointerType>(ToType))
1946 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1947 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001948}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001949
Mike Stump11289f42009-09-09 15:08:12 +00001950static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001951 bool InOverloadResolution,
1952 ASTContext &Context) {
1953 // Handle value-dependent integral null pointer constants correctly.
1954 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1955 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001956 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001957 return !InOverloadResolution;
1958
Douglas Gregor56751b52009-09-25 04:25:58 +00001959 return Expr->isNullPointerConstant(Context,
1960 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1961 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001962}
Mike Stump11289f42009-09-09 15:08:12 +00001963
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001964/// IsPointerConversion - Determines whether the conversion of the
1965/// expression From, which has the (possibly adjusted) type FromType,
1966/// can be converted to the type ToType via a pointer conversion (C++
1967/// 4.10). If so, returns true and places the converted type (that
1968/// might differ from ToType in its cv-qualifiers at some level) into
1969/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001970///
Douglas Gregora29dc052008-11-27 01:19:21 +00001971/// This routine also supports conversions to and from block pointers
1972/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1973/// pointers to interfaces. FIXME: Once we've determined the
1974/// appropriate overloading rules for Objective-C, we may want to
1975/// split the Objective-C checks into a different routine; however,
1976/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001977/// conversions, so for now they live here. IncompatibleObjC will be
1978/// set if the conversion is an allowed Objective-C conversion that
1979/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001980bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001981 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001982 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001983 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001984 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001985 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1986 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001987 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001988
Mike Stump11289f42009-09-09 15:08:12 +00001989 // Conversion from a null pointer constant to any Objective-C pointer type.
1990 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001991 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001992 ConvertedType = ToType;
1993 return true;
1994 }
1995
Douglas Gregor231d1c62008-11-27 00:15:41 +00001996 // Blocks: Block pointers can be converted to void*.
1997 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001998 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001999 ConvertedType = ToType;
2000 return true;
2001 }
2002 // Blocks: A null pointer constant can be converted to a block
2003 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002004 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002005 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002006 ConvertedType = ToType;
2007 return true;
2008 }
2009
Sebastian Redl576fd422009-05-10 18:38:11 +00002010 // If the left-hand-side is nullptr_t, the right side can be a null
2011 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002012 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002013 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002014 ConvertedType = ToType;
2015 return true;
2016 }
2017
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002018 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002019 if (!ToTypePtr)
2020 return false;
2021
2022 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002023 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002024 ConvertedType = ToType;
2025 return true;
2026 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002027
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002028 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002029 // , including objective-c pointers.
2030 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002031 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002032 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002033 ConvertedType = BuildSimilarlyQualifiedPointerType(
2034 FromType->getAs<ObjCObjectPointerType>(),
2035 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002036 ToType, Context);
2037 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002038 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002039 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002040 if (!FromTypePtr)
2041 return false;
2042
2043 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002044
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002045 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002046 // pointer conversion, so don't do all of the work below.
2047 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2048 return false;
2049
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002050 // An rvalue of type "pointer to cv T," where T is an object type,
2051 // can be converted to an rvalue of type "pointer to cv void" (C++
2052 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002053 if (FromPointeeType->isIncompleteOrObjectType() &&
2054 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002055 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002056 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002057 ToType, Context,
2058 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002059 return true;
2060 }
2061
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002062 // MSVC allows implicit function to void* type conversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002063 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002064 ToPointeeType->isVoidType()) {
2065 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2066 ToPointeeType,
2067 ToType, Context);
2068 return true;
2069 }
2070
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002071 // When we're overloading in C, we allow a special kind of pointer
2072 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002073 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002074 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002075 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002076 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002077 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002078 return true;
2079 }
2080
Douglas Gregor5c407d92008-10-23 00:40:37 +00002081 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002082 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002083 // An rvalue of type "pointer to cv D," where D is a class type,
2084 // can be converted to an rvalue of type "pointer to cv B," where
2085 // B is a base class (clause 10) of D. If B is an inaccessible
2086 // (clause 11) or ambiguous (10.2) base class of D, a program that
2087 // necessitates this conversion is ill-formed. The result of the
2088 // conversion is a pointer to the base class sub-object of the
2089 // derived class object. The null pointer value is converted to
2090 // the null pointer value of the destination type.
2091 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002092 // Note that we do not check for ambiguity or inaccessibility
2093 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002094 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002095 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002096 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002097 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00002098 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002099 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002100 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002101 ToType, Context);
2102 return true;
2103 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002104
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002105 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2106 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2107 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2108 ToPointeeType,
2109 ToType, Context);
2110 return true;
2111 }
2112
Douglas Gregora119f102008-12-19 19:13:09 +00002113 return false;
2114}
Douglas Gregoraec25842011-04-26 23:16:46 +00002115
2116/// \brief Adopt the given qualifiers for the given type.
2117static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2118 Qualifiers TQs = T.getQualifiers();
2119
2120 // Check whether qualifiers already match.
2121 if (TQs == Qs)
2122 return T;
2123
2124 if (Qs.compatiblyIncludes(TQs))
2125 return Context.getQualifiedType(T, Qs);
2126
2127 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2128}
Douglas Gregora119f102008-12-19 19:13:09 +00002129
2130/// isObjCPointerConversion - Determines whether this is an
2131/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2132/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002133bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002134 QualType& ConvertedType,
2135 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002136 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002137 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002138
Douglas Gregoraec25842011-04-26 23:16:46 +00002139 // The set of qualifiers on the type we're converting from.
2140 Qualifiers FromQualifiers = FromType.getQualifiers();
2141
Steve Naroff7cae42b2009-07-10 23:34:53 +00002142 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002143 const ObjCObjectPointerType* ToObjCPtr =
2144 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002145 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002146 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002147
Steve Naroff7cae42b2009-07-10 23:34:53 +00002148 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002149 // If the pointee types are the same (ignoring qualifications),
2150 // then this is not a pointer conversion.
2151 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2152 FromObjCPtr->getPointeeType()))
2153 return false;
2154
Douglas Gregorab209d82015-07-07 03:58:42 +00002155 // Conversion between Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002156 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002157 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2158 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002159 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002160 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2161 FromObjCPtr->getPointeeType()))
2162 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002163 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002164 ToObjCPtr->getPointeeType(),
2165 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002166 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002167 return true;
2168 }
2169
2170 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2171 // Okay: this is some kind of implicit downcast of Objective-C
2172 // interfaces, which is permitted. However, we're going to
2173 // complain about it.
2174 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002175 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002176 ToObjCPtr->getPointeeType(),
2177 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002178 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002179 return true;
2180 }
Mike Stump11289f42009-09-09 15:08:12 +00002181 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002182 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002183 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002184 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002185 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002186 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002187 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002188 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002189 // to a block pointer type.
2190 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002191 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002192 return true;
2193 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002194 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002195 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002196 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002197 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002198 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002199 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002200 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002201 return true;
2202 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002203 else
Douglas Gregora119f102008-12-19 19:13:09 +00002204 return false;
2205
Douglas Gregor033f56d2008-12-23 00:53:59 +00002206 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002207 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002208 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002209 else if (const BlockPointerType *FromBlockPtr =
2210 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002211 FromPointeeType = FromBlockPtr->getPointeeType();
2212 else
Douglas Gregora119f102008-12-19 19:13:09 +00002213 return false;
2214
Douglas Gregora119f102008-12-19 19:13:09 +00002215 // If we have pointers to pointers, recursively check whether this
2216 // is an Objective-C conversion.
2217 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2218 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2219 IncompatibleObjC)) {
2220 // We always complain about this conversion.
2221 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002222 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002223 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002224 return true;
2225 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002226 // Allow conversion of pointee being objective-c pointer to another one;
2227 // as in I* to id.
2228 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2229 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2230 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2231 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002232
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002233 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002234 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002235 return true;
2236 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002237
Douglas Gregor033f56d2008-12-23 00:53:59 +00002238 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002239 // differences in the argument and result types are in Objective-C
2240 // pointer conversions. If so, we permit the conversion (but
2241 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002242 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002243 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002244 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002245 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002246 if (FromFunctionType && ToFunctionType) {
2247 // If the function types are exactly the same, this isn't an
2248 // Objective-C pointer conversion.
2249 if (Context.getCanonicalType(FromPointeeType)
2250 == Context.getCanonicalType(ToPointeeType))
2251 return false;
2252
2253 // Perform the quick checks that will tell us whether these
2254 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002255 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002256 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2257 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2258 return false;
2259
2260 bool HasObjCConversion = false;
Alp Toker314cc812014-01-25 16:55:45 +00002261 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2262 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregora119f102008-12-19 19:13:09 +00002263 // Okay, the types match exactly. Nothing to do.
Alp Toker314cc812014-01-25 16:55:45 +00002264 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2265 ToFunctionType->getReturnType(),
Douglas Gregora119f102008-12-19 19:13:09 +00002266 ConvertedType, IncompatibleObjC)) {
2267 // Okay, we have an Objective-C pointer conversion.
2268 HasObjCConversion = true;
2269 } else {
2270 // Function types are too different. Abort.
2271 return false;
2272 }
Mike Stump11289f42009-09-09 15:08:12 +00002273
Douglas Gregora119f102008-12-19 19:13:09 +00002274 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002275 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002276 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002277 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2278 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002279 if (Context.getCanonicalType(FromArgType)
2280 == Context.getCanonicalType(ToArgType)) {
2281 // Okay, the types match exactly. Nothing to do.
2282 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2283 ConvertedType, IncompatibleObjC)) {
2284 // Okay, we have an Objective-C pointer conversion.
2285 HasObjCConversion = true;
2286 } else {
2287 // Argument types are too different. Abort.
2288 return false;
2289 }
2290 }
2291
2292 if (HasObjCConversion) {
2293 // We had an Objective-C conversion. Allow this pointer
2294 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002295 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002296 IncompatibleObjC = true;
2297 return true;
2298 }
2299 }
2300
Sebastian Redl72b597d2009-01-25 19:43:20 +00002301 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002302}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002303
John McCall31168b02011-06-15 23:02:42 +00002304/// \brief Determine whether this is an Objective-C writeback conversion,
2305/// used for parameter passing when performing automatic reference counting.
2306///
2307/// \param FromType The type we're converting form.
2308///
2309/// \param ToType The type we're converting to.
2310///
2311/// \param ConvertedType The type that will be produced after applying
2312/// this conversion.
2313bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2314 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002315 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002316 Context.hasSameUnqualifiedType(FromType, ToType))
2317 return false;
2318
2319 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2320 QualType ToPointee;
2321 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2322 ToPointee = ToPointer->getPointeeType();
2323 else
2324 return false;
2325
2326 Qualifiers ToQuals = ToPointee.getQualifiers();
2327 if (!ToPointee->isObjCLifetimeType() ||
2328 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002329 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002330 return false;
2331
2332 // Argument must be a pointer to __strong to __weak.
2333 QualType FromPointee;
2334 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2335 FromPointee = FromPointer->getPointeeType();
2336 else
2337 return false;
2338
2339 Qualifiers FromQuals = FromPointee.getQualifiers();
2340 if (!FromPointee->isObjCLifetimeType() ||
2341 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2342 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2343 return false;
2344
2345 // Make sure that we have compatible qualifiers.
2346 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2347 if (!ToQuals.compatiblyIncludes(FromQuals))
2348 return false;
2349
2350 // Remove qualifiers from the pointee type we're converting from; they
2351 // aren't used in the compatibility check belong, and we'll be adding back
2352 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2353 FromPointee = FromPointee.getUnqualifiedType();
2354
2355 // The unqualified form of the pointee types must be compatible.
2356 ToPointee = ToPointee.getUnqualifiedType();
2357 bool IncompatibleObjC;
2358 if (Context.typesAreCompatible(FromPointee, ToPointee))
2359 FromPointee = ToPointee;
2360 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2361 IncompatibleObjC))
2362 return false;
2363
2364 /// \brief Construct the type we're converting to, which is a pointer to
2365 /// __autoreleasing pointee.
2366 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2367 ConvertedType = Context.getPointerType(FromPointee);
2368 return true;
2369}
2370
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002371bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2372 QualType& ConvertedType) {
2373 QualType ToPointeeType;
2374 if (const BlockPointerType *ToBlockPtr =
2375 ToType->getAs<BlockPointerType>())
2376 ToPointeeType = ToBlockPtr->getPointeeType();
2377 else
2378 return false;
2379
2380 QualType FromPointeeType;
2381 if (const BlockPointerType *FromBlockPtr =
2382 FromType->getAs<BlockPointerType>())
2383 FromPointeeType = FromBlockPtr->getPointeeType();
2384 else
2385 return false;
2386 // We have pointer to blocks, check whether the only
2387 // differences in the argument and result types are in Objective-C
2388 // pointer conversions. If so, we permit the conversion.
2389
2390 const FunctionProtoType *FromFunctionType
2391 = FromPointeeType->getAs<FunctionProtoType>();
2392 const FunctionProtoType *ToFunctionType
2393 = ToPointeeType->getAs<FunctionProtoType>();
2394
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002395 if (!FromFunctionType || !ToFunctionType)
2396 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002397
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002398 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002399 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002400
2401 // Perform the quick checks that will tell us whether these
2402 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002403 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002404 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2405 return false;
2406
2407 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2408 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2409 if (FromEInfo != ToEInfo)
2410 return false;
2411
2412 bool IncompatibleObjC = false;
Alp Toker314cc812014-01-25 16:55:45 +00002413 if (Context.hasSameType(FromFunctionType->getReturnType(),
2414 ToFunctionType->getReturnType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002415 // Okay, the types match exactly. Nothing to do.
2416 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002417 QualType RHS = FromFunctionType->getReturnType();
2418 QualType LHS = ToFunctionType->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002419 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002420 !RHS.hasQualifiers() && LHS.hasQualifiers())
2421 LHS = LHS.getUnqualifiedType();
2422
2423 if (Context.hasSameType(RHS,LHS)) {
2424 // OK exact match.
2425 } else if (isObjCPointerConversion(RHS, LHS,
2426 ConvertedType, IncompatibleObjC)) {
2427 if (IncompatibleObjC)
2428 return false;
2429 // Okay, we have an Objective-C pointer conversion.
2430 }
2431 else
2432 return false;
2433 }
2434
2435 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002436 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002437 ArgIdx != NumArgs; ++ArgIdx) {
2438 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002439 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2440 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002441 if (Context.hasSameType(FromArgType, ToArgType)) {
2442 // Okay, the types match exactly. Nothing to do.
2443 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2444 ConvertedType, IncompatibleObjC)) {
2445 if (IncompatibleObjC)
2446 return false;
2447 // Okay, we have an Objective-C pointer conversion.
2448 } else
2449 // Argument types are too different. Abort.
2450 return false;
2451 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002452 if (LangOpts.ObjCAutoRefCount &&
2453 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2454 ToFunctionType))
2455 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002456
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002457 ConvertedType = ToType;
2458 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002459}
2460
Richard Trieucaff2472011-11-23 22:32:32 +00002461enum {
2462 ft_default,
2463 ft_different_class,
2464 ft_parameter_arity,
2465 ft_parameter_mismatch,
2466 ft_return_type,
2467 ft_qualifer_mismatch
2468};
2469
2470/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2471/// function types. Catches different number of parameter, mismatch in
2472/// parameter types, and different return types.
2473void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2474 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002475 // If either type is not valid, include no extra info.
2476 if (FromType.isNull() || ToType.isNull()) {
2477 PDiag << ft_default;
2478 return;
2479 }
2480
Richard Trieucaff2472011-11-23 22:32:32 +00002481 // Get the function type from the pointers.
2482 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2483 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2484 *ToMember = ToType->getAs<MemberPointerType>();
Richard Trieu9098c9f2014-05-22 01:39:16 +00002485 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
Richard Trieucaff2472011-11-23 22:32:32 +00002486 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2487 << QualType(FromMember->getClass(), 0);
2488 return;
2489 }
2490 FromType = FromMember->getPointeeType();
2491 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002492 }
2493
Richard Trieu96ed5b62011-12-13 23:19:45 +00002494 if (FromType->isPointerType())
2495 FromType = FromType->getPointeeType();
2496 if (ToType->isPointerType())
2497 ToType = ToType->getPointeeType();
2498
2499 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002500 FromType = FromType.getNonReferenceType();
2501 ToType = ToType.getNonReferenceType();
2502
Richard Trieucaff2472011-11-23 22:32:32 +00002503 // Don't print extra info for non-specialized template functions.
2504 if (FromType->isInstantiationDependentType() &&
2505 !FromType->getAs<TemplateSpecializationType>()) {
2506 PDiag << ft_default;
2507 return;
2508 }
2509
Richard Trieu96ed5b62011-12-13 23:19:45 +00002510 // No extra info for same types.
2511 if (Context.hasSameType(FromType, ToType)) {
2512 PDiag << ft_default;
2513 return;
2514 }
2515
Richard Trieucaff2472011-11-23 22:32:32 +00002516 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2517 *ToFunction = ToType->getAs<FunctionProtoType>();
2518
2519 // Both types need to be function types.
2520 if (!FromFunction || !ToFunction) {
2521 PDiag << ft_default;
2522 return;
2523 }
2524
Alp Toker9cacbab2014-01-20 20:26:09 +00002525 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2526 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2527 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002528 return;
2529 }
2530
2531 // Handle different parameter types.
2532 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002533 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002534 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002535 << ToFunction->getParamType(ArgPos)
2536 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002537 return;
2538 }
2539
2540 // Handle different return type.
Alp Toker314cc812014-01-25 16:55:45 +00002541 if (!Context.hasSameType(FromFunction->getReturnType(),
2542 ToFunction->getReturnType())) {
2543 PDiag << ft_return_type << ToFunction->getReturnType()
2544 << FromFunction->getReturnType();
Richard Trieucaff2472011-11-23 22:32:32 +00002545 return;
2546 }
2547
2548 unsigned FromQuals = FromFunction->getTypeQuals(),
2549 ToQuals = ToFunction->getTypeQuals();
2550 if (FromQuals != ToQuals) {
2551 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2552 return;
2553 }
2554
2555 // Unable to find a difference, so add no extra info.
2556 PDiag << ft_default;
2557}
2558
Alp Toker9cacbab2014-01-20 20:26:09 +00002559/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002560/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002561/// they have same number of arguments. If the parameters are different,
2562/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002563bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2564 const FunctionProtoType *NewType,
2565 unsigned *ArgPos) {
2566 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2567 N = NewType->param_type_begin(),
2568 E = OldType->param_type_end();
2569 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002570 if (!Context.hasSameType(O->getUnqualifiedType(),
2571 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002572 if (ArgPos)
2573 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002574 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002575 }
2576 }
2577 return true;
2578}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002579
Douglas Gregor39c16d42008-10-24 04:54:22 +00002580/// CheckPointerConversion - Check the pointer conversion from the
2581/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002582/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002583/// conversions for which IsPointerConversion has already returned
2584/// true. It returns true and produces a diagnostic if there was an
2585/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002586bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002587 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002588 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002589 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002590 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002591 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002592
John McCall8cb679e2010-11-15 09:13:47 +00002593 Kind = CK_BitCast;
2594
David Blaikie1c7c8f72012-08-08 17:33:31 +00002595 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
Argyrios Kyrtzidis3e3305d2014-02-02 05:26:43 +00002596 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
David Blaikie1c7c8f72012-08-08 17:33:31 +00002597 Expr::NPCK_ZeroExpression) {
2598 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2599 DiagRuntimeBehavior(From->getExprLoc(), From,
2600 PDiag(diag::warn_impcast_bool_to_null_pointer)
2601 << ToType << From->getSourceRange());
2602 else if (!isUnevaluatedContext())
2603 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2604 << ToType << From->getSourceRange();
2605 }
John McCall9320b872011-09-09 05:25:32 +00002606 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2607 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002608 QualType FromPointeeType = FromPtrType->getPointeeType(),
2609 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002610
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002611 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2612 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002613 // We must have a derived-to-base conversion. Check an
2614 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002615 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2616 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002617 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002618 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002619 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002620
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002621 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002622 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002623 }
2624 }
John McCall9320b872011-09-09 05:25:32 +00002625 } else if (const ObjCObjectPointerType *ToPtrType =
2626 ToType->getAs<ObjCObjectPointerType>()) {
2627 if (const ObjCObjectPointerType *FromPtrType =
2628 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002629 // Objective-C++ conversions are always okay.
2630 // FIXME: We should have a different class of conversions for the
2631 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002632 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002633 return false;
John McCall9320b872011-09-09 05:25:32 +00002634 } else if (FromType->isBlockPointerType()) {
2635 Kind = CK_BlockPointerToObjCPointerCast;
2636 } else {
2637 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002638 }
John McCall9320b872011-09-09 05:25:32 +00002639 } else if (ToType->isBlockPointerType()) {
2640 if (!FromType->isBlockPointerType())
2641 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002642 }
John McCall8cb679e2010-11-15 09:13:47 +00002643
2644 // We shouldn't fall into this case unless it's valid for other
2645 // reasons.
2646 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2647 Kind = CK_NullToPointer;
2648
Douglas Gregor39c16d42008-10-24 04:54:22 +00002649 return false;
2650}
2651
Sebastian Redl72b597d2009-01-25 19:43:20 +00002652/// IsMemberPointerConversion - Determines whether the conversion of the
2653/// expression From, which has the (possibly adjusted) type FromType, can be
2654/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2655/// If so, returns true and places the converted type (that might differ from
2656/// ToType in its cv-qualifiers at some level) into ConvertedType.
2657bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002658 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002659 bool InOverloadResolution,
2660 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002661 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002662 if (!ToTypePtr)
2663 return false;
2664
2665 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002666 if (From->isNullPointerConstant(Context,
2667 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2668 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002669 ConvertedType = ToType;
2670 return true;
2671 }
2672
2673 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002674 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002675 if (!FromTypePtr)
2676 return false;
2677
2678 // A pointer to member of B can be converted to a pointer to member of D,
2679 // where D is derived from B (C++ 4.11p2).
2680 QualType FromClass(FromTypePtr->getClass(), 0);
2681 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002682
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002683 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002684 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002685 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002686 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2687 ToClass.getTypePtr());
2688 return true;
2689 }
2690
2691 return false;
2692}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002693
Sebastian Redl72b597d2009-01-25 19:43:20 +00002694/// CheckMemberPointerConversion - Check the member pointer conversion from the
2695/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002696/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002697/// for which IsMemberPointerConversion has already returned true. It returns
2698/// true and produces a diagnostic if there was an error, or returns false
2699/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002700bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002701 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002702 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002703 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002704 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002705 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002706 if (!FromPtrType) {
2707 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002708 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002709 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002710 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002711 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002712 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002713 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002714
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002715 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002716 assert(ToPtrType && "No member pointer cast has a target type "
2717 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002718
Sebastian Redled8f2002009-01-28 18:33:18 +00002719 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2720 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002721
Sebastian Redled8f2002009-01-28 18:33:18 +00002722 // FIXME: What about dependent types?
2723 assert(FromClass->isRecordType() && "Pointer into non-class.");
2724 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002725
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002726 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002727 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002728 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2729 assert(DerivationOkay &&
2730 "Should not have been called if derivation isn't OK.");
2731 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002732
Sebastian Redled8f2002009-01-28 18:33:18 +00002733 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2734 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002735 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2736 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2737 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2738 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002739 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002740
Douglas Gregor89ee6822009-02-28 01:32:25 +00002741 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002742 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2743 << FromClass << ToClass << QualType(VBase, 0)
2744 << From->getSourceRange();
2745 return true;
2746 }
2747
John McCall5b0829a2010-02-10 09:31:12 +00002748 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002749 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2750 Paths.front(),
2751 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002752
Anders Carlssond7923c62009-08-22 23:33:40 +00002753 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002754 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002755 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002756 return false;
2757}
2758
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002759/// Determine whether the lifetime conversion between the two given
2760/// qualifiers sets is nontrivial.
2761static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2762 Qualifiers ToQuals) {
2763 // Converting anything to const __unsafe_unretained is trivial.
2764 if (ToQuals.hasConst() &&
2765 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2766 return false;
2767
2768 return true;
2769}
2770
Douglas Gregor9a657932008-10-21 23:43:52 +00002771/// IsQualificationConversion - Determines whether the conversion from
2772/// an rvalue of type FromType to ToType is a qualification conversion
2773/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002774///
2775/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2776/// when the qualification conversion involves a change in the Objective-C
2777/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002778bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002779Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002780 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002781 FromType = Context.getCanonicalType(FromType);
2782 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002783 ObjCLifetimeConversion = false;
2784
Douglas Gregor9a657932008-10-21 23:43:52 +00002785 // If FromType and ToType are the same type, this is not a
2786 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002787 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002788 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002789
Douglas Gregor9a657932008-10-21 23:43:52 +00002790 // (C++ 4.4p4):
2791 // A conversion can add cv-qualifiers at levels other than the first
2792 // in multi-level pointers, subject to the following rules: [...]
2793 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002794 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002795 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002796 // Within each iteration of the loop, we check the qualifiers to
2797 // determine if this still looks like a qualification
2798 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002799 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002800 // until there are no more pointers or pointers-to-members left to
2801 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002802 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002803
Douglas Gregor90609aa2011-04-25 18:40:17 +00002804 Qualifiers FromQuals = FromType.getQualifiers();
2805 Qualifiers ToQuals = ToType.getQualifiers();
2806
John McCall31168b02011-06-15 23:02:42 +00002807 // Objective-C ARC:
2808 // Check Objective-C lifetime conversions.
2809 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2810 UnwrappedAnyPointer) {
2811 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002812 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2813 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00002814 FromQuals.removeObjCLifetime();
2815 ToQuals.removeObjCLifetime();
2816 } else {
2817 // Qualification conversions cannot cast between different
2818 // Objective-C lifetime qualifiers.
2819 return false;
2820 }
2821 }
2822
Douglas Gregorf30053d2011-05-08 06:09:53 +00002823 // Allow addition/removal of GC attributes but not changing GC attributes.
2824 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2825 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2826 FromQuals.removeObjCGCAttr();
2827 ToQuals.removeObjCGCAttr();
2828 }
2829
Douglas Gregor9a657932008-10-21 23:43:52 +00002830 // -- for every j > 0, if const is in cv 1,j then const is in cv
2831 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002832 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002833 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002834
Douglas Gregor9a657932008-10-21 23:43:52 +00002835 // -- if the cv 1,j and cv 2,j are different, then const is in
2836 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002837 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002838 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002839 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002840
Douglas Gregor9a657932008-10-21 23:43:52 +00002841 // Keep track of whether all prior cv-qualifiers in the "to" type
2842 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002843 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002844 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002845 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002846
2847 // We are left with FromType and ToType being the pointee types
2848 // after unwrapping the original FromType and ToType the same number
2849 // of types. If we unwrapped any pointers, and if FromType and
2850 // ToType have the same unqualified type (since we checked
2851 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002852 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002853}
2854
Douglas Gregorc79862f2012-04-12 17:51:55 +00002855/// \brief - Determine whether this is a conversion from a scalar type to an
2856/// atomic type.
2857///
2858/// If successful, updates \c SCS's second and third steps in the conversion
2859/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00002860static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2861 bool InOverloadResolution,
2862 StandardConversionSequence &SCS,
2863 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00002864 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2865 if (!ToAtomic)
2866 return false;
2867
2868 StandardConversionSequence InnerSCS;
2869 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2870 InOverloadResolution, InnerSCS,
2871 CStyle, /*AllowObjCWritebackConversion=*/false))
2872 return false;
2873
2874 SCS.Second = InnerSCS.Second;
2875 SCS.setToType(1, InnerSCS.getToType(1));
2876 SCS.Third = InnerSCS.Third;
2877 SCS.QualificationIncludesObjCLifetime
2878 = InnerSCS.QualificationIncludesObjCLifetime;
2879 SCS.setToType(2, InnerSCS.getToType(2));
2880 return true;
2881}
2882
Sebastian Redle5417162012-03-27 18:33:03 +00002883static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2884 CXXConstructorDecl *Constructor,
2885 QualType Type) {
2886 const FunctionProtoType *CtorType =
2887 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002888 if (CtorType->getNumParams() > 0) {
2889 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00002890 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2891 return true;
2892 }
2893 return false;
2894}
2895
Sebastian Redl82ace982012-02-11 23:51:08 +00002896static OverloadingResult
2897IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2898 CXXRecordDecl *To,
2899 UserDefinedConversionSequence &User,
2900 OverloadCandidateSet &CandidateSet,
2901 bool AllowExplicit) {
David Blaikieff7d47a2012-12-19 00:45:41 +00002902 DeclContext::lookup_result R = S.LookupConstructors(To);
2903 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl82ace982012-02-11 23:51:08 +00002904 Con != ConEnd; ++Con) {
2905 NamedDecl *D = *Con;
2906 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2907
2908 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00002909 CXXConstructorDecl *Constructor = nullptr;
Sebastian Redl82ace982012-02-11 23:51:08 +00002910 FunctionTemplateDecl *ConstructorTmpl
2911 = dyn_cast<FunctionTemplateDecl>(D);
2912 if (ConstructorTmpl)
2913 Constructor
2914 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2915 else
2916 Constructor = cast<CXXConstructorDecl>(D);
2917
2918 bool Usable = !Constructor->isInvalidDecl() &&
2919 S.isInitListConstructor(Constructor) &&
2920 (AllowExplicit || !Constructor->isExplicit());
2921 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00002922 // If the first argument is (a reference to) the target type,
2923 // suppress conversions.
2924 bool SuppressUserConversions =
2925 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl82ace982012-02-11 23:51:08 +00002926 if (ConstructorTmpl)
2927 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00002928 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002929 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002930 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002931 else
2932 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002933 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002934 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002935 }
2936 }
2937
2938 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2939
2940 OverloadCandidateSet::iterator Best;
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00002941 switch (auto Result =
2942 CandidateSet.BestViableFunction(S, From->getLocStart(),
2943 Best, true)) {
2944 case OR_Deleted:
Sebastian Redl82ace982012-02-11 23:51:08 +00002945 case OR_Success: {
2946 // Record the standard conversion we used and the conversion function.
2947 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00002948 QualType ThisType = Constructor->getThisType(S.Context);
2949 // Initializer lists don't have conversions as such.
2950 User.Before.setAsIdentityConversion();
2951 User.HadMultipleCandidates = HadMultipleCandidates;
2952 User.ConversionFunction = Constructor;
2953 User.FoundConversionFunction = Best->FoundDecl;
2954 User.After.setAsIdentityConversion();
2955 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2956 User.After.setAllToTypes(ToType);
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00002957 return Result;
Sebastian Redl82ace982012-02-11 23:51:08 +00002958 }
2959
2960 case OR_No_Viable_Function:
2961 return OR_No_Viable_Function;
Sebastian Redl82ace982012-02-11 23:51:08 +00002962 case OR_Ambiguous:
2963 return OR_Ambiguous;
2964 }
2965
2966 llvm_unreachable("Invalid OverloadResult!");
2967}
2968
Douglas Gregor576e98c2009-01-30 23:27:23 +00002969/// Determines whether there is a user-defined conversion sequence
2970/// (C++ [over.ics.user]) that converts expression From to the type
2971/// ToType. If such a conversion exists, User will contain the
2972/// user-defined conversion sequence that performs such a conversion
2973/// and this routine will return true. Otherwise, this routine returns
2974/// false and User is unspecified.
2975///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002976/// \param AllowExplicit true if the conversion should consider C++0x
2977/// "explicit" conversion functions as well as non-explicit conversion
2978/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00002979///
2980/// \param AllowObjCConversionOnExplicit true if the conversion should
2981/// allow an extra Objective-C pointer conversion on uses of explicit
2982/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00002983static OverloadingResult
2984IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00002985 UserDefinedConversionSequence &User,
2986 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00002987 bool AllowExplicit,
2988 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00002989 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor4b60a152013-11-07 22:34:54 +00002990
Douglas Gregor5ab11652010-04-17 22:01:05 +00002991 // Whether we will only visit constructors.
2992 bool ConstructorsOnly = false;
2993
2994 // If the type we are conversion to is a class type, enumerate its
2995 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002996 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002997 // C++ [over.match.ctor]p1:
2998 // When objects of class type are direct-initialized (8.5), or
2999 // copy-initialized from an expression of the same or a
3000 // derived class type (8.5), overload resolution selects the
3001 // constructor. [...] For copy-initialization, the candidate
3002 // functions are all the converting constructors (12.3.1) of
3003 // that class. The argument list is the expression-list within
3004 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003005 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003006 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00003007 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003008 ConstructorsOnly = true;
3009
Benjamin Kramer90633e32012-11-23 17:04:52 +00003010 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00003011 // RequireCompleteType may have returned true due to some invalid decl
3012 // during template instantiation, but ToType may be complete enough now
3013 // to try to recover.
3014 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003015 // We're not going to find any constructors.
3016 } else if (CXXRecordDecl *ToRecordDecl
3017 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003018
3019 Expr **Args = &From;
3020 unsigned NumArgs = 1;
3021 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003022 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003023 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003024 OverloadingResult Result = IsInitializerListConstructorConversion(
3025 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3026 if (Result != OR_No_Viable_Function)
3027 return Result;
3028 // Never mind.
3029 CandidateSet.clear();
3030
3031 // If we're list-initializing, we pass the individual elements as
3032 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003033 Args = InitList->getInits();
3034 NumArgs = InitList->getNumInits();
3035 ListInitializing = true;
3036 }
3037
David Blaikieff7d47a2012-12-19 00:45:41 +00003038 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3039 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregor89ee6822009-02-28 01:32:25 +00003040 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003041 NamedDecl *D = *Con;
3042 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3043
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003044 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003045 CXXConstructorDecl *Constructor = nullptr;
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003046 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00003047 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003048 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003049 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003050 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3051 else
John McCalla0296f72010-03-19 07:35:19 +00003052 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003053
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003054 bool Usable = !Constructor->isInvalidDecl();
3055 if (ListInitializing)
3056 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3057 else
3058 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3059 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003060 bool SuppressUserConversions = !ConstructorsOnly;
3061 if (SuppressUserConversions && ListInitializing) {
3062 SuppressUserConversions = false;
3063 if (NumArgs == 1) {
3064 // If the first argument is (a reference to) the target type,
3065 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003066 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3067 S.Context, Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003068 }
3069 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003070 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00003071 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003072 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003073 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003074 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003075 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003076 // Allow one user-defined conversion when user specifies a
3077 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00003078 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003079 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003080 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003081 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003082 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003083 }
3084 }
3085
Douglas Gregor5ab11652010-04-17 22:01:05 +00003086 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003087 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003088 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003089 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003090 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003091 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003092 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003093 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3094 // Add all of the conversion functions as candidates.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003095 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3096 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003097 DeclAccessPair FoundDecl = I.getPair();
3098 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003099 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3100 if (isa<UsingShadowDecl>(D))
3101 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3102
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003103 CXXConversionDecl *Conv;
3104 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003105 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3106 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003107 else
John McCallda4458e2010-03-31 01:36:47 +00003108 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003109
3110 if (AllowExplicit || !Conv->isExplicit()) {
3111 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003112 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3113 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003114 CandidateSet,
3115 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003116 else
John McCall5c32be02010-08-24 20:38:10 +00003117 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003118 From, ToType, CandidateSet,
3119 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003120 }
3121 }
3122 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003123 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003124
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003125 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3126
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003127 OverloadCandidateSet::iterator Best;
Richard Smith48372b62015-01-27 03:30:40 +00003128 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3129 Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003130 case OR_Success:
Richard Smith48372b62015-01-27 03:30:40 +00003131 case OR_Deleted:
John McCall5c32be02010-08-24 20:38:10 +00003132 // Record the standard conversion we used and the conversion function.
3133 if (CXXConstructorDecl *Constructor
3134 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3135 // C++ [over.ics.user]p1:
3136 // If the user-defined conversion is specified by a
3137 // constructor (12.3.1), the initial standard conversion
3138 // sequence converts the source type to the type required by
3139 // the argument of the constructor.
3140 //
3141 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003142 if (isa<InitListExpr>(From)) {
3143 // Initializer lists don't have conversions as such.
3144 User.Before.setAsIdentityConversion();
3145 } else {
3146 if (Best->Conversions[0].isEllipsis())
3147 User.EllipsisConversion = true;
3148 else {
3149 User.Before = Best->Conversions[0].Standard;
3150 User.EllipsisConversion = false;
3151 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003152 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003153 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003154 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003155 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003156 User.After.setAsIdentityConversion();
3157 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3158 User.After.setAllToTypes(ToType);
Richard Smith48372b62015-01-27 03:30:40 +00003159 return Result;
David Blaikie8a40f702012-01-17 06:56:22 +00003160 }
3161 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003162 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3163 // C++ [over.ics.user]p1:
3164 //
3165 // [...] If the user-defined conversion is specified by a
3166 // conversion function (12.3.2), the initial standard
3167 // conversion sequence converts the source type to the
3168 // implicit object parameter of the conversion function.
3169 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003170 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003171 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003172 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003173 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003174
John McCall5c32be02010-08-24 20:38:10 +00003175 // C++ [over.ics.user]p2:
3176 // The second standard conversion sequence converts the
3177 // result of the user-defined conversion to the target type
3178 // for the sequence. Since an implicit conversion sequence
3179 // is an initialization, the special rules for
3180 // initialization by user-defined conversion apply when
3181 // selecting the best user-defined conversion for a
3182 // user-defined conversion sequence (see 13.3.3 and
3183 // 13.3.3.1).
3184 User.After = Best->FinalConversion;
Richard Smith48372b62015-01-27 03:30:40 +00003185 return Result;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003186 }
David Blaikie8a40f702012-01-17 06:56:22 +00003187 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003188
John McCall5c32be02010-08-24 20:38:10 +00003189 case OR_No_Viable_Function:
3190 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003191
John McCall5c32be02010-08-24 20:38:10 +00003192 case OR_Ambiguous:
3193 return OR_Ambiguous;
3194 }
3195
David Blaikie8a40f702012-01-17 06:56:22 +00003196 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003197}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003198
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003199bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003200Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003201 ImplicitConversionSequence ICS;
Richard Smith100b24a2014-04-17 01:52:14 +00003202 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3203 OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003204 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003205 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003206 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003207 if (OvResult == OR_Ambiguous)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003208 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3209 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003210 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003211 if (!RequireCompleteType(From->getLocStart(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003212 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003213 From->getType(), From->getSourceRange()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003214 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00003215 << false << From->getType() << From->getSourceRange() << ToType;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003216 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003217 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003218 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003219 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003220}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003221
Douglas Gregor2837aa22012-02-22 17:32:19 +00003222/// \brief Compare the user-defined conversion functions or constructors
3223/// of two user-defined conversion sequences to determine whether any ordering
3224/// is possible.
3225static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003226compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003227 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003228 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003229 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003230
Douglas Gregor2837aa22012-02-22 17:32:19 +00003231 // Objective-C++:
3232 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003233 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003234 // respectively, always prefer the conversion to a function pointer,
3235 // because the function pointer is more lightweight and is more likely
3236 // to keep code working.
Ted Kremenek8d265c22014-04-01 07:23:18 +00003237 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003238 if (!Conv1)
3239 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003240
Douglas Gregor2837aa22012-02-22 17:32:19 +00003241 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3242 if (!Conv2)
3243 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003244
Douglas Gregor2837aa22012-02-22 17:32:19 +00003245 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3246 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3247 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3248 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003249 return Block1 ? ImplicitConversionSequence::Worse
3250 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003251 }
3252
3253 return ImplicitConversionSequence::Indistinguishable;
3254}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003255
3256static bool hasDeprecatedStringLiteralToCharPtrConversion(
3257 const ImplicitConversionSequence &ICS) {
3258 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3259 (ICS.isUserDefined() &&
3260 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3261}
3262
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003263/// CompareImplicitConversionSequences - Compare two implicit
3264/// conversion sequences to determine whether one is better than the
3265/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003266static ImplicitConversionSequence::CompareKind
3267CompareImplicitConversionSequences(Sema &S,
3268 const ImplicitConversionSequence& ICS1,
3269 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003270{
3271 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3272 // conversion sequences (as defined in 13.3.3.1)
3273 // -- a standard conversion sequence (13.3.3.1.1) is a better
3274 // conversion sequence than a user-defined conversion sequence or
3275 // an ellipsis conversion sequence, and
3276 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3277 // conversion sequence than an ellipsis conversion sequence
3278 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003279 //
John McCall0d1da222010-01-12 00:44:57 +00003280 // C++0x [over.best.ics]p10:
3281 // For the purpose of ranking implicit conversion sequences as
3282 // described in 13.3.3.2, the ambiguous conversion sequence is
3283 // treated as a user-defined sequence that is indistinguishable
3284 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003285
3286 // String literal to 'char *' conversion has been deprecated in C++03. It has
3287 // been removed from C++11. We still accept this conversion, if it happens at
3288 // the best viable function. Otherwise, this conversion is considered worse
3289 // than ellipsis conversion. Consider this as an extension; this is not in the
3290 // standard. For example:
3291 //
3292 // int &f(...); // #1
3293 // void f(char*); // #2
3294 // void g() { int &r = f("foo"); }
3295 //
3296 // In C++03, we pick #2 as the best viable function.
3297 // In C++11, we pick #1 as the best viable function, because ellipsis
3298 // conversion is better than string-literal to char* conversion (since there
3299 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3300 // convert arguments, #2 would be the best viable function in C++11.
3301 // If the best viable function has this conversion, a warning will be issued
3302 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3303
3304 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3305 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3306 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3307 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3308 ? ImplicitConversionSequence::Worse
3309 : ImplicitConversionSequence::Better;
3310
Douglas Gregor5ab11652010-04-17 22:01:05 +00003311 if (ICS1.getKindRank() < ICS2.getKindRank())
3312 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003313 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003314 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003315
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003316 // The following checks require both conversion sequences to be of
3317 // the same kind.
3318 if (ICS1.getKind() != ICS2.getKind())
3319 return ImplicitConversionSequence::Indistinguishable;
3320
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003321 ImplicitConversionSequence::CompareKind Result =
3322 ImplicitConversionSequence::Indistinguishable;
3323
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003324 // Two implicit conversion sequences of the same form are
3325 // indistinguishable conversion sequences unless one of the
3326 // following rules apply: (C++ 13.3.3.2p3):
Larisse Voufo19d08672015-01-27 18:47:05 +00003327
3328 // List-initialization sequence L1 is a better conversion sequence than
3329 // list-initialization sequence L2 if:
3330 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3331 // if not that,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00003332 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
Larisse Voufo19d08672015-01-27 18:47:05 +00003333 // and N1 is smaller than N2.,
3334 // even if one of the other rules in this paragraph would otherwise apply.
3335 if (!ICS1.isBad()) {
3336 if (ICS1.isStdInitializerListElement() &&
3337 !ICS2.isStdInitializerListElement())
3338 return ImplicitConversionSequence::Better;
3339 if (!ICS1.isStdInitializerListElement() &&
3340 ICS2.isStdInitializerListElement())
3341 return ImplicitConversionSequence::Worse;
3342 }
3343
John McCall0d1da222010-01-12 00:44:57 +00003344 if (ICS1.isStandard())
Larisse Voufo19d08672015-01-27 18:47:05 +00003345 // Standard conversion sequence S1 is a better conversion sequence than
3346 // standard conversion sequence S2 if [...]
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003347 Result = CompareStandardConversionSequences(S,
3348 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003349 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003350 // User-defined conversion sequence U1 is a better conversion
3351 // sequence than another user-defined conversion sequence U2 if
3352 // they contain the same user-defined conversion function or
3353 // constructor and if the second standard conversion sequence of
3354 // U1 is better than the second standard conversion sequence of
3355 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003356 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003357 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003358 Result = CompareStandardConversionSequences(S,
3359 ICS1.UserDefined.After,
3360 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003361 else
3362 Result = compareConversionFunctions(S,
3363 ICS1.UserDefined.ConversionFunction,
3364 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003365 }
3366
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003367 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003368}
3369
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003370static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3371 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3372 Qualifiers Quals;
3373 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003374 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003375 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003376
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003377 return Context.hasSameUnqualifiedType(T1, T2);
3378}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003379
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003380// Per 13.3.3.2p3, compare the given standard conversion sequences to
3381// determine if one is a proper subset of the other.
3382static ImplicitConversionSequence::CompareKind
3383compareStandardConversionSubsets(ASTContext &Context,
3384 const StandardConversionSequence& SCS1,
3385 const StandardConversionSequence& SCS2) {
3386 ImplicitConversionSequence::CompareKind Result
3387 = ImplicitConversionSequence::Indistinguishable;
3388
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003389 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003390 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003391 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3392 return ImplicitConversionSequence::Better;
3393 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3394 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003395
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003396 if (SCS1.Second != SCS2.Second) {
3397 if (SCS1.Second == ICK_Identity)
3398 Result = ImplicitConversionSequence::Better;
3399 else if (SCS2.Second == ICK_Identity)
3400 Result = ImplicitConversionSequence::Worse;
3401 else
3402 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003403 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003404 return ImplicitConversionSequence::Indistinguishable;
3405
3406 if (SCS1.Third == SCS2.Third) {
3407 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3408 : ImplicitConversionSequence::Indistinguishable;
3409 }
3410
3411 if (SCS1.Third == ICK_Identity)
3412 return Result == ImplicitConversionSequence::Worse
3413 ? ImplicitConversionSequence::Indistinguishable
3414 : ImplicitConversionSequence::Better;
3415
3416 if (SCS2.Third == ICK_Identity)
3417 return Result == ImplicitConversionSequence::Better
3418 ? ImplicitConversionSequence::Indistinguishable
3419 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003420
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003421 return ImplicitConversionSequence::Indistinguishable;
3422}
3423
Douglas Gregore696ebb2011-01-26 14:52:12 +00003424/// \brief Determine whether one of the given reference bindings is better
3425/// than the other based on what kind of bindings they are.
Richard Smith19172c42014-07-14 02:28:44 +00003426static bool
3427isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3428 const StandardConversionSequence &SCS2) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003429 // C++0x [over.ics.rank]p3b4:
3430 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3431 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003432 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003433 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003434 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003435 // reference*.
3436 //
3437 // FIXME: Rvalue references. We're going rogue with the above edits,
3438 // because the semantics in the current C++0x working paper (N3225 at the
3439 // time of this writing) break the standard definition of std::forward
3440 // and std::reference_wrapper when dealing with references to functions.
3441 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003442 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3443 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3444 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003445
Douglas Gregore696ebb2011-01-26 14:52:12 +00003446 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3447 SCS2.IsLvalueReference) ||
3448 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
Richard Smith19172c42014-07-14 02:28:44 +00003449 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
Douglas Gregore696ebb2011-01-26 14:52:12 +00003450}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003451
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003452/// CompareStandardConversionSequences - Compare two standard
3453/// conversion sequences to determine whether one is better than the
3454/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003455static ImplicitConversionSequence::CompareKind
3456CompareStandardConversionSequences(Sema &S,
3457 const StandardConversionSequence& SCS1,
3458 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003459{
3460 // Standard conversion sequence S1 is a better conversion sequence
3461 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3462
3463 // -- S1 is a proper subsequence of S2 (comparing the conversion
3464 // sequences in the canonical form defined by 13.3.3.1.1,
3465 // excluding any Lvalue Transformation; the identity conversion
3466 // sequence is considered to be a subsequence of any
3467 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003468 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003469 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003470 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003471
3472 // -- the rank of S1 is better than the rank of S2 (by the rules
3473 // defined below), or, if not that,
3474 ImplicitConversionRank Rank1 = SCS1.getRank();
3475 ImplicitConversionRank Rank2 = SCS2.getRank();
3476 if (Rank1 < Rank2)
3477 return ImplicitConversionSequence::Better;
3478 else if (Rank2 < Rank1)
3479 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003480
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003481 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3482 // are indistinguishable unless one of the following rules
3483 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003484
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003485 // A conversion that is not a conversion of a pointer, or
3486 // pointer to member, to bool is better than another conversion
3487 // that is such a conversion.
3488 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3489 return SCS2.isPointerConversionToBool()
3490 ? ImplicitConversionSequence::Better
3491 : ImplicitConversionSequence::Worse;
3492
Douglas Gregor5c407d92008-10-23 00:40:37 +00003493 // C++ [over.ics.rank]p4b2:
3494 //
3495 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003496 // conversion of B* to A* is better than conversion of B* to
3497 // void*, and conversion of A* to void* is better than conversion
3498 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003499 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003500 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003501 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003502 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003503 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3504 // Exactly one of the conversion sequences is a conversion to
3505 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003506 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3507 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003508 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3509 // Neither conversion sequence converts to a void pointer; compare
3510 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003511 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00003512 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003513 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003514 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3515 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003516 // Both conversion sequences are conversions to void
3517 // pointers. Compare the source types to determine if there's an
3518 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003519 QualType FromType1 = SCS1.getFromType();
3520 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003521
3522 // Adjust the types we're converting from via the array-to-pointer
3523 // conversion, if we need to.
3524 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003525 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003526 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003527 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003528
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003529 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3530 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003531
John McCall5c32be02010-08-24 20:38:10 +00003532 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003533 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003534 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003535 return ImplicitConversionSequence::Worse;
3536
3537 // Objective-C++: If one interface is more specific than the
3538 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003539 const ObjCObjectPointerType* FromObjCPtr1
3540 = FromType1->getAs<ObjCObjectPointerType>();
3541 const ObjCObjectPointerType* FromObjCPtr2
3542 = FromType2->getAs<ObjCObjectPointerType>();
3543 if (FromObjCPtr1 && FromObjCPtr2) {
3544 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3545 FromObjCPtr2);
3546 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3547 FromObjCPtr1);
3548 if (AssignLeft != AssignRight) {
3549 return AssignLeft? ImplicitConversionSequence::Better
3550 : ImplicitConversionSequence::Worse;
3551 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003552 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003553 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003554
3555 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3556 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003557 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003558 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003559 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003560
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003561 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003562 // Check for a better reference binding based on the kind of bindings.
3563 if (isBetterReferenceBindingKind(SCS1, SCS2))
3564 return ImplicitConversionSequence::Better;
3565 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3566 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003567
Sebastian Redlb28b4072009-03-22 23:49:27 +00003568 // C++ [over.ics.rank]p3b4:
3569 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3570 // which the references refer are the same type except for
3571 // top-level cv-qualifiers, and the type to which the reference
3572 // initialized by S2 refers is more cv-qualified than the type
3573 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003574 QualType T1 = SCS1.getToType(2);
3575 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003576 T1 = S.Context.getCanonicalType(T1);
3577 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003578 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003579 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3580 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003581 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003582 // Objective-C++ ARC: If the references refer to objects with different
3583 // lifetimes, prefer bindings that don't change lifetime.
3584 if (SCS1.ObjCLifetimeConversionBinding !=
3585 SCS2.ObjCLifetimeConversionBinding) {
3586 return SCS1.ObjCLifetimeConversionBinding
3587 ? ImplicitConversionSequence::Worse
3588 : ImplicitConversionSequence::Better;
3589 }
3590
Chandler Carruth8e543b32010-12-12 08:17:55 +00003591 // If the type is an array type, promote the element qualifiers to the
3592 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003593 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003594 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003595 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003596 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003597 if (T2.isMoreQualifiedThan(T1))
3598 return ImplicitConversionSequence::Better;
3599 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003600 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003601 }
3602 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003603
Francois Pichet08d2fa02011-09-18 21:37:37 +00003604 // In Microsoft mode, prefer an integral conversion to a
3605 // floating-to-integral conversion if the integral conversion
3606 // is between types of the same size.
3607 // For example:
3608 // void f(float);
3609 // void f(int);
3610 // int main {
3611 // long a;
3612 // f(a);
3613 // }
3614 // Here, MSVC will call f(int) instead of generating a compile error
3615 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003616 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3617 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003618 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003619 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003620 return ImplicitConversionSequence::Better;
3621
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003622 return ImplicitConversionSequence::Indistinguishable;
3623}
3624
3625/// CompareQualificationConversions - Compares two standard conversion
3626/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003627/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
Richard Smith17c00b42014-11-12 01:24:00 +00003628static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003629CompareQualificationConversions(Sema &S,
3630 const StandardConversionSequence& SCS1,
3631 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003632 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003633 // -- S1 and S2 differ only in their qualification conversion and
3634 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3635 // cv-qualification signature of type T1 is a proper subset of
3636 // the cv-qualification signature of type T2, and S1 is not the
3637 // deprecated string literal array-to-pointer conversion (4.2).
3638 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3639 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3640 return ImplicitConversionSequence::Indistinguishable;
3641
3642 // FIXME: the example in the standard doesn't use a qualification
3643 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003644 QualType T1 = SCS1.getToType(2);
3645 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003646 T1 = S.Context.getCanonicalType(T1);
3647 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003648 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003649 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3650 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003651
3652 // If the types are the same, we won't learn anything by unwrapped
3653 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003654 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003655 return ImplicitConversionSequence::Indistinguishable;
3656
Chandler Carruth607f38e2009-12-29 07:16:59 +00003657 // If the type is an array type, promote the element qualifiers to the type
3658 // for comparison.
3659 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003660 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003661 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003662 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003663
Mike Stump11289f42009-09-09 15:08:12 +00003664 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003665 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003666
3667 // Objective-C++ ARC:
3668 // Prefer qualification conversions not involving a change in lifetime
3669 // to qualification conversions that do not change lifetime.
3670 if (SCS1.QualificationIncludesObjCLifetime !=
3671 SCS2.QualificationIncludesObjCLifetime) {
3672 Result = SCS1.QualificationIncludesObjCLifetime
3673 ? ImplicitConversionSequence::Worse
3674 : ImplicitConversionSequence::Better;
3675 }
3676
John McCall5c32be02010-08-24 20:38:10 +00003677 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003678 // Within each iteration of the loop, we check the qualifiers to
3679 // determine if this still looks like a qualification
3680 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003681 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003682 // until there are no more pointers or pointers-to-members left
3683 // to unwrap. This essentially mimics what
3684 // IsQualificationConversion does, but here we're checking for a
3685 // strict subset of qualifiers.
3686 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3687 // The qualifiers are the same, so this doesn't tell us anything
3688 // about how the sequences rank.
3689 ;
3690 else if (T2.isMoreQualifiedThan(T1)) {
3691 // T1 has fewer qualifiers, so it could be the better sequence.
3692 if (Result == ImplicitConversionSequence::Worse)
3693 // Neither has qualifiers that are a subset of the other's
3694 // qualifiers.
3695 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003696
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003697 Result = ImplicitConversionSequence::Better;
3698 } else if (T1.isMoreQualifiedThan(T2)) {
3699 // T2 has fewer qualifiers, so it could be the better sequence.
3700 if (Result == ImplicitConversionSequence::Better)
3701 // Neither has qualifiers that are a subset of the other's
3702 // qualifiers.
3703 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003704
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003705 Result = ImplicitConversionSequence::Worse;
3706 } else {
3707 // Qualifiers are disjoint.
3708 return ImplicitConversionSequence::Indistinguishable;
3709 }
3710
3711 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003712 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003713 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003714 }
3715
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003716 // Check that the winning standard conversion sequence isn't using
3717 // the deprecated string literal array to pointer conversion.
3718 switch (Result) {
3719 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003720 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003721 Result = ImplicitConversionSequence::Indistinguishable;
3722 break;
3723
3724 case ImplicitConversionSequence::Indistinguishable:
3725 break;
3726
3727 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003728 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003729 Result = ImplicitConversionSequence::Indistinguishable;
3730 break;
3731 }
3732
3733 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003734}
3735
Douglas Gregor5c407d92008-10-23 00:40:37 +00003736/// CompareDerivedToBaseConversions - Compares two standard conversion
3737/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003738/// various kinds of derived-to-base conversions (C++
3739/// [over.ics.rank]p4b3). As part of these checks, we also look at
3740/// conversions between Objective-C interface types.
Richard Smith17c00b42014-11-12 01:24:00 +00003741static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003742CompareDerivedToBaseConversions(Sema &S,
3743 const StandardConversionSequence& SCS1,
3744 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003745 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003746 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003747 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003748 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003749
3750 // Adjust the types we're converting from via the array-to-pointer
3751 // conversion, if we need to.
3752 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003753 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003754 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003755 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003756
3757 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003758 FromType1 = S.Context.getCanonicalType(FromType1);
3759 ToType1 = S.Context.getCanonicalType(ToType1);
3760 FromType2 = S.Context.getCanonicalType(FromType2);
3761 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003762
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003763 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003764 //
3765 // If class B is derived directly or indirectly from class A and
3766 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003767 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003768 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003769 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003770 SCS2.Second == ICK_Pointer_Conversion &&
3771 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3772 FromType1->isPointerType() && FromType2->isPointerType() &&
3773 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003774 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003775 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003776 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003777 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003778 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003779 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003780 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003781 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003782
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003783 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003784 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003785 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003786 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003787 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003788 return ImplicitConversionSequence::Worse;
3789 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003790
3791 // -- conversion of B* to A* is better than conversion of C* to A*,
3792 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003793 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003794 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003795 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003796 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003797 }
3798 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3799 SCS2.Second == ICK_Pointer_Conversion) {
3800 const ObjCObjectPointerType *FromPtr1
3801 = FromType1->getAs<ObjCObjectPointerType>();
3802 const ObjCObjectPointerType *FromPtr2
3803 = FromType2->getAs<ObjCObjectPointerType>();
3804 const ObjCObjectPointerType *ToPtr1
3805 = ToType1->getAs<ObjCObjectPointerType>();
3806 const ObjCObjectPointerType *ToPtr2
3807 = ToType2->getAs<ObjCObjectPointerType>();
3808
3809 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3810 // Apply the same conversion ranking rules for Objective-C pointer types
3811 // that we do for C++ pointers to class types. However, we employ the
3812 // Objective-C pseudo-subtyping relationship used for assignment of
3813 // Objective-C pointer types.
3814 bool FromAssignLeft
3815 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3816 bool FromAssignRight
3817 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3818 bool ToAssignLeft
3819 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3820 bool ToAssignRight
3821 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3822
3823 // A conversion to an a non-id object pointer type or qualified 'id'
3824 // type is better than a conversion to 'id'.
3825 if (ToPtr1->isObjCIdType() &&
3826 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3827 return ImplicitConversionSequence::Worse;
3828 if (ToPtr2->isObjCIdType() &&
3829 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3830 return ImplicitConversionSequence::Better;
3831
3832 // A conversion to a non-id object pointer type is better than a
3833 // conversion to a qualified 'id' type
3834 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3835 return ImplicitConversionSequence::Worse;
3836 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3837 return ImplicitConversionSequence::Better;
3838
3839 // A conversion to an a non-Class object pointer type or qualified 'Class'
3840 // type is better than a conversion to 'Class'.
3841 if (ToPtr1->isObjCClassType() &&
3842 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3843 return ImplicitConversionSequence::Worse;
3844 if (ToPtr2->isObjCClassType() &&
3845 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3846 return ImplicitConversionSequence::Better;
3847
3848 // A conversion to a non-Class object pointer type is better than a
3849 // conversion to a qualified 'Class' type.
3850 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3851 return ImplicitConversionSequence::Worse;
3852 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3853 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003854
Douglas Gregor058d3de2011-01-31 18:51:41 +00003855 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3856 if (S.Context.hasSameType(FromType1, FromType2) &&
3857 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3858 (ToAssignLeft != ToAssignRight))
3859 return ToAssignLeft? ImplicitConversionSequence::Worse
3860 : ImplicitConversionSequence::Better;
3861
3862 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3863 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3864 (FromAssignLeft != FromAssignRight))
3865 return FromAssignLeft? ImplicitConversionSequence::Better
3866 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003867 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003868 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003869
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003870 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003871 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3872 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3873 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003874 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003875 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003876 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003877 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003878 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003879 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003880 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003881 ToType2->getAs<MemberPointerType>();
3882 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3883 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3884 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3885 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3886 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3887 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3888 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3889 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003890 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003891 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003892 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003893 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003894 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003895 return ImplicitConversionSequence::Better;
3896 }
3897 // conversion of B::* to C::* is better than conversion of A::* to C::*
3898 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003899 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003900 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003901 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003902 return ImplicitConversionSequence::Worse;
3903 }
3904 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003905
Douglas Gregor5ab11652010-04-17 22:01:05 +00003906 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003907 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003908 // -- binding of an expression of type C to a reference of type
3909 // B& is better than binding an expression of type C to a
3910 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003911 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3912 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3913 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003914 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003915 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003916 return ImplicitConversionSequence::Worse;
3917 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003918
Douglas Gregor2fe98832008-11-03 19:09:14 +00003919 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003920 // -- binding of an expression of type B to a reference of type
3921 // A& is better than binding an expression of type C to a
3922 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003923 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3924 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3925 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003926 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003927 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003928 return ImplicitConversionSequence::Worse;
3929 }
3930 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003931
Douglas Gregor5c407d92008-10-23 00:40:37 +00003932 return ImplicitConversionSequence::Indistinguishable;
3933}
3934
Douglas Gregor45bb4832013-03-26 23:36:30 +00003935/// \brief Determine whether the given type is valid, e.g., it is not an invalid
3936/// C++ class.
3937static bool isTypeValid(QualType T) {
3938 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3939 return !Record->isInvalidDecl();
3940
3941 return true;
3942}
3943
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003944/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3945/// determine whether they are reference-related,
3946/// reference-compatible, reference-compatible with added
3947/// qualification, or incompatible, for use in C++ initialization by
3948/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3949/// type, and the first type (T1) is the pointee type of the reference
3950/// type being initialized.
3951Sema::ReferenceCompareResult
3952Sema::CompareReferenceRelationship(SourceLocation Loc,
3953 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003954 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003955 bool &ObjCConversion,
3956 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003957 assert(!OrigT1->isReferenceType() &&
3958 "T1 must be the pointee type of the reference type");
3959 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3960
3961 QualType T1 = Context.getCanonicalType(OrigT1);
3962 QualType T2 = Context.getCanonicalType(OrigT2);
3963 Qualifiers T1Quals, T2Quals;
3964 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3965 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3966
3967 // C++ [dcl.init.ref]p4:
3968 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3969 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3970 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003971 DerivedToBase = false;
3972 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003973 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003974 if (UnqualT1 == UnqualT2) {
3975 // Nothing to do.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003976 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00003977 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
3978 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003979 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003980 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3981 UnqualT2->isObjCObjectOrInterfaceType() &&
3982 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3983 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003984 else
3985 return Ref_Incompatible;
3986
3987 // At this point, we know that T1 and T2 are reference-related (at
3988 // least).
3989
3990 // If the type is an array type, promote the element qualifiers to the type
3991 // for comparison.
3992 if (isa<ArrayType>(T1) && T1Quals)
3993 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3994 if (isa<ArrayType>(T2) && T2Quals)
3995 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3996
3997 // C++ [dcl.init.ref]p4:
3998 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3999 // reference-related to T2 and cv1 is the same cv-qualification
4000 // as, or greater cv-qualification than, cv2. For purposes of
4001 // overload resolution, cases for which cv1 is greater
4002 // cv-qualification than cv2 are identified as
4003 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004004 //
4005 // Note that we also require equivalence of Objective-C GC and address-space
4006 // qualifiers when performing these computations, so that e.g., an int in
4007 // address space 1 is not reference-compatible with an int in address
4008 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004009 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4010 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004011 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4012 ObjCLifetimeConversion = true;
4013
John McCall31168b02011-06-15 23:02:42 +00004014 T1Quals.removeObjCLifetime();
4015 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004016 }
4017
Douglas Gregord517d552011-04-28 17:56:11 +00004018 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004019 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00004020 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004021 return Ref_Compatible_With_Added_Qualification;
4022 else
4023 return Ref_Related;
4024}
4025
Douglas Gregor836a7e82010-08-11 02:15:33 +00004026/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004027/// with DeclType. Return true if something definite is found.
4028static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004029FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4030 QualType DeclType, SourceLocation DeclLoc,
4031 Expr *Init, QualType T2, bool AllowRvalues,
4032 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004033 assert(T2->isRecordType() && "Can only find conversions of record types.");
4034 CXXRecordDecl *T2RecordDecl
4035 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4036
Richard Smith100b24a2014-04-17 01:52:14 +00004037 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004038 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4039 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004040 NamedDecl *D = *I;
4041 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4042 if (isa<UsingShadowDecl>(D))
4043 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4044
4045 FunctionTemplateDecl *ConvTemplate
4046 = dyn_cast<FunctionTemplateDecl>(D);
4047 CXXConversionDecl *Conv;
4048 if (ConvTemplate)
4049 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4050 else
4051 Conv = cast<CXXConversionDecl>(D);
4052
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004053 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004054 // explicit conversions, skip it.
4055 if (!AllowExplicit && Conv->isExplicit())
4056 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004057
Douglas Gregor836a7e82010-08-11 02:15:33 +00004058 if (AllowRvalues) {
4059 bool DerivedToBase = false;
4060 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004061 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004062
4063 // If we are initializing an rvalue reference, don't permit conversion
4064 // functions that return lvalues.
4065 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4066 const ReferenceType *RefType
4067 = Conv->getConversionType()->getAs<LValueReferenceType>();
4068 if (RefType && !RefType->getPointeeType()->isFunctionType())
4069 continue;
4070 }
4071
Douglas Gregor836a7e82010-08-11 02:15:33 +00004072 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004073 S.CompareReferenceRelationship(
4074 DeclLoc,
4075 Conv->getConversionType().getNonReferenceType()
4076 .getUnqualifiedType(),
4077 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004078 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004079 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004080 continue;
4081 } else {
4082 // If the conversion function doesn't return a reference type,
4083 // it can't be considered for this conversion. An rvalue reference
4084 // is only acceptable if its referencee is a function type.
4085
4086 const ReferenceType *RefType =
4087 Conv->getConversionType()->getAs<ReferenceType>();
4088 if (!RefType ||
4089 (!RefType->isLValueReferenceType() &&
4090 !RefType->getPointeeType()->isFunctionType()))
4091 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004092 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004093
Douglas Gregor836a7e82010-08-11 02:15:33 +00004094 if (ConvTemplate)
4095 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004096 Init, DeclType, CandidateSet,
4097 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004098 else
4099 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004100 DeclType, CandidateSet,
4101 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004102 }
4103
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004104 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4105
Sebastian Redld92badf2010-06-30 18:13:39 +00004106 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004107 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004108 case OR_Success:
4109 // C++ [over.ics.ref]p1:
4110 //
4111 // [...] If the parameter binds directly to the result of
4112 // applying a conversion function to the argument
4113 // expression, the implicit conversion sequence is a
4114 // user-defined conversion sequence (13.3.3.1.2), with the
4115 // second standard conversion sequence either an identity
4116 // conversion or, if the conversion function returns an
4117 // entity of a type that is a derived class of the parameter
4118 // type, a derived-to-base Conversion.
4119 if (!Best->FinalConversion.DirectBinding)
4120 return false;
4121
4122 ICS.setUserDefined();
4123 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4124 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004125 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004126 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004127 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004128 ICS.UserDefined.EllipsisConversion = false;
4129 assert(ICS.UserDefined.After.ReferenceBinding &&
4130 ICS.UserDefined.After.DirectBinding &&
4131 "Expected a direct reference binding!");
4132 return true;
4133
4134 case OR_Ambiguous:
4135 ICS.setAmbiguous();
4136 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4137 Cand != CandidateSet.end(); ++Cand)
4138 if (Cand->Viable)
4139 ICS.Ambiguous.addConversion(Cand->Function);
4140 return true;
4141
4142 case OR_No_Viable_Function:
4143 case OR_Deleted:
4144 // There was no suitable conversion, or we found a deleted
4145 // conversion; continue with other checks.
4146 return false;
4147 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004148
David Blaikie8a40f702012-01-17 06:56:22 +00004149 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004150}
4151
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004152/// \brief Compute an implicit conversion sequence for reference
4153/// initialization.
4154static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004155TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004156 SourceLocation DeclLoc,
4157 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004158 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004159 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4160
4161 // Most paths end in a failed conversion.
4162 ImplicitConversionSequence ICS;
4163 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4164
4165 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4166 QualType T2 = Init->getType();
4167
4168 // If the initializer is the address of an overloaded function, try
4169 // to resolve the overloaded function. If all goes well, T2 is the
4170 // type of the resulting function.
4171 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4172 DeclAccessPair Found;
4173 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4174 false, Found))
4175 T2 = Fn->getType();
4176 }
4177
4178 // Compute some basic properties of the types and the initializer.
4179 bool isRValRef = DeclType->isRValueReferenceType();
4180 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004181 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004182 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004183 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004184 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004185 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004186 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004187
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004188
Sebastian Redld92badf2010-06-30 18:13:39 +00004189 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004190 // A reference to type "cv1 T1" is initialized by an expression
4191 // of type "cv2 T2" as follows:
4192
Sebastian Redld92badf2010-06-30 18:13:39 +00004193 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004194 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004195 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4196 // reference-compatible with "cv2 T2," or
4197 //
4198 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4199 if (InitCategory.isLValue() &&
4200 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004201 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004202 // When a parameter of reference type binds directly (8.5.3)
4203 // to an argument expression, the implicit conversion sequence
4204 // is the identity conversion, unless the argument expression
4205 // has a type that is a derived class of the parameter type,
4206 // in which case the implicit conversion sequence is a
4207 // derived-to-base Conversion (13.3.3.1).
4208 ICS.setStandard();
4209 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004210 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4211 : ObjCConversion? ICK_Compatible_Conversion
4212 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004213 ICS.Standard.Third = ICK_Identity;
4214 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4215 ICS.Standard.setToType(0, T2);
4216 ICS.Standard.setToType(1, T1);
4217 ICS.Standard.setToType(2, T1);
4218 ICS.Standard.ReferenceBinding = true;
4219 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004220 ICS.Standard.IsLvalueReference = !isRValRef;
4221 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4222 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004223 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004224 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004225 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004226 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004227
Sebastian Redld92badf2010-06-30 18:13:39 +00004228 // Nothing more to do: the inaccessibility/ambiguity check for
4229 // derived-to-base conversions is suppressed when we're
4230 // computing the implicit conversion sequence (C++
4231 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004232 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004233 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004234
Sebastian Redld92badf2010-06-30 18:13:39 +00004235 // -- has a class type (i.e., T2 is a class type), where T1 is
4236 // not reference-related to T2, and can be implicitly
4237 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4238 // is reference-compatible with "cv3 T3" 92) (this
4239 // conversion is selected by enumerating the applicable
4240 // conversion functions (13.3.1.6) and choosing the best
4241 // one through overload resolution (13.3)),
4242 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004243 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004244 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004245 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4246 Init, T2, /*AllowRvalues=*/false,
4247 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004248 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004249 }
4250 }
4251
Sebastian Redld92badf2010-06-30 18:13:39 +00004252 // -- Otherwise, the reference shall be an lvalue reference to a
4253 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004254 // shall be an rvalue reference.
Richard Smithce4f6082012-05-24 04:29:20 +00004255 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004256 return ICS;
4257
Douglas Gregorf143cd52011-01-24 16:14:37 +00004258 // -- If the initializer expression
4259 //
4260 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004261 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004262 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4263 (InitCategory.isXValue() ||
4264 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4265 (InitCategory.isLValue() && T2->isFunctionType()))) {
4266 ICS.setStandard();
4267 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004268 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004269 : ObjCConversion? ICK_Compatible_Conversion
4270 : ICK_Identity;
4271 ICS.Standard.Third = ICK_Identity;
4272 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4273 ICS.Standard.setToType(0, T2);
4274 ICS.Standard.setToType(1, T1);
4275 ICS.Standard.setToType(2, T1);
4276 ICS.Standard.ReferenceBinding = true;
4277 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4278 // binding unless we're binding to a class prvalue.
4279 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4280 // allow the use of rvalue references in C++98/03 for the benefit of
4281 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004282 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004283 S.getLangOpts().CPlusPlus11 ||
Richard Smithb94afe12014-07-14 19:54:05 +00004284 !(InitCategory.isPRValue() || T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004285 ICS.Standard.IsLvalueReference = !isRValRef;
4286 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004287 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004288 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004289 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004290 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004291 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004292 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004293 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004294
Douglas Gregorf143cd52011-01-24 16:14:37 +00004295 // -- has a class type (i.e., T2 is a class type), where T1 is not
4296 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004297 // an xvalue, class prvalue, or function lvalue of type
4298 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004299 // "cv3 T3",
4300 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004301 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004302 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004303 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004304 // class subobject).
4305 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004306 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004307 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4308 Init, T2, /*AllowRvalues=*/true,
4309 AllowExplicit)) {
4310 // In the second case, if the reference is an rvalue reference
4311 // and the second standard conversion sequence of the
4312 // user-defined conversion sequence includes an lvalue-to-rvalue
4313 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004314 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004315 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4316 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4317
Douglas Gregor95273c32011-01-21 16:36:05 +00004318 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004319 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004320
Richard Smith19172c42014-07-14 02:28:44 +00004321 // A temporary of function type cannot be created; don't even try.
4322 if (T1->isFunctionType())
4323 return ICS;
4324
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004325 // -- Otherwise, a temporary of type "cv1 T1" is created and
4326 // initialized from the initializer expression using the
4327 // rules for a non-reference copy initialization (8.5). The
4328 // reference is then bound to the temporary. If T1 is
4329 // reference-related to T2, cv1 must be the same
4330 // cv-qualification as, or greater cv-qualification than,
4331 // cv2; otherwise, the program is ill-formed.
4332 if (RefRelationship == Sema::Ref_Related) {
4333 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4334 // we would be reference-compatible or reference-compatible with
4335 // added qualification. But that wasn't the case, so the reference
4336 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004337 //
4338 // Note that we only want to check address spaces and cvr-qualifiers here.
4339 // ObjC GC and lifetime qualifiers aren't important.
4340 Qualifiers T1Quals = T1.getQualifiers();
4341 Qualifiers T2Quals = T2.getQualifiers();
4342 T1Quals.removeObjCGCAttr();
4343 T1Quals.removeObjCLifetime();
4344 T2Quals.removeObjCGCAttr();
4345 T2Quals.removeObjCLifetime();
4346 if (!T1Quals.compatiblyIncludes(T2Quals))
4347 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004348 }
4349
4350 // If at least one of the types is a class type, the types are not
4351 // related, and we aren't allowed any user conversions, the
4352 // reference binding fails. This case is important for breaking
4353 // recursion, since TryImplicitConversion below will attempt to
4354 // create a temporary through the use of a copy constructor.
4355 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4356 (T1->isRecordType() || T2->isRecordType()))
4357 return ICS;
4358
Douglas Gregorcba72b12011-01-21 05:18:22 +00004359 // If T1 is reference-related to T2 and the reference is an rvalue
4360 // reference, the initializer expression shall not be an lvalue.
4361 if (RefRelationship >= Sema::Ref_Related &&
4362 isRValRef && Init->Classify(S.Context).isLValue())
4363 return ICS;
4364
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004365 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004366 // When a parameter of reference type is not bound directly to
4367 // an argument expression, the conversion sequence is the one
4368 // required to convert the argument expression to the
4369 // underlying type of the reference according to
4370 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4371 // to copy-initializing a temporary of the underlying type with
4372 // the argument expression. Any difference in top-level
4373 // cv-qualification is subsumed by the initialization itself
4374 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004375 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4376 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004377 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004378 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004379 /*AllowObjCWritebackConversion=*/false,
4380 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004381
4382 // Of course, that's still a reference binding.
4383 if (ICS.isStandard()) {
4384 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004385 ICS.Standard.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004386 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004387 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004388 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004389 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004390 } else if (ICS.isUserDefined()) {
Richard Smith19172c42014-07-14 02:28:44 +00004391 const ReferenceType *LValRefType =
4392 ICS.UserDefined.ConversionFunction->getReturnType()
4393 ->getAs<LValueReferenceType>();
4394
4395 // C++ [over.ics.ref]p3:
4396 // Except for an implicit object parameter, for which see 13.3.1, a
4397 // standard conversion sequence cannot be formed if it requires [...]
4398 // binding an rvalue reference to an lvalue other than a function
4399 // lvalue.
4400 // Note that the function case is not possible here.
4401 if (DeclType->isRValueReferenceType() && LValRefType) {
4402 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4403 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4404 // reference to an rvalue!
4405 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4406 return ICS;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004407 }
Richard Smith19172c42014-07-14 02:28:44 +00004408
Ismail Pazarbasi99afd962014-01-24 10:54:12 +00004409 ICS.UserDefined.Before.setAsIdentityConversion();
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004410 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004411 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004412 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4413 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004414 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4415 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004416 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004417
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004418 return ICS;
4419}
4420
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004421static ImplicitConversionSequence
4422TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4423 bool SuppressUserConversions,
4424 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004425 bool AllowObjCWritebackConversion,
4426 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004427
4428/// TryListConversion - Try to copy-initialize a value of type ToType from the
4429/// initializer list From.
4430static ImplicitConversionSequence
4431TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4432 bool SuppressUserConversions,
4433 bool InOverloadResolution,
4434 bool AllowObjCWritebackConversion) {
4435 // C++11 [over.ics.list]p1:
4436 // When an argument is an initializer list, it is not an expression and
4437 // special rules apply for converting it to a parameter type.
4438
4439 ImplicitConversionSequence Result;
4440 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4441
Sebastian Redl09edce02012-01-23 22:09:39 +00004442 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004443 // initialized from init lists.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004444 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004445 return Result;
4446
Larisse Voufo19d08672015-01-27 18:47:05 +00004447 // Per DR1467:
4448 // If the parameter type is a class X and the initializer list has a single
4449 // element of type cv U, where U is X or a class derived from X, the
4450 // implicit conversion sequence is the one required to convert the element
4451 // to the parameter type.
4452 //
4453 // Otherwise, if the parameter type is a character array [... ]
4454 // and the initializer list has a single element that is an
4455 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4456 // implicit conversion sequence is the identity conversion.
4457 if (From->getNumInits() == 1) {
4458 if (ToType->isRecordType()) {
4459 QualType InitType = From->getInit(0)->getType();
4460 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4461 S.IsDerivedFrom(InitType, ToType))
4462 return TryCopyInitialization(S, From->getInit(0), ToType,
4463 SuppressUserConversions,
4464 InOverloadResolution,
4465 AllowObjCWritebackConversion);
4466 }
Richard Smith1bbaba82015-01-27 23:23:39 +00004467 // FIXME: Check the other conditions here: array of character type,
4468 // initializer is a string literal.
4469 if (ToType->isArrayType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004470 InitializedEntity Entity =
4471 InitializedEntity::InitializeParameter(S.Context, ToType,
4472 /*Consumed=*/false);
4473 if (S.CanPerformCopyInitialization(Entity, From)) {
4474 Result.setStandard();
4475 Result.Standard.setAsIdentityConversion();
4476 Result.Standard.setFromType(ToType);
4477 Result.Standard.setAllToTypes(ToType);
4478 return Result;
4479 }
4480 }
4481 }
4482
4483 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004484 // C++11 [over.ics.list]p2:
4485 // If the parameter type is std::initializer_list<X> or "array of X" and
4486 // all the elements can be implicitly converted to X, the implicit
4487 // conversion sequence is the worst conversion necessary to convert an
4488 // element of the list to X.
Larisse Voufo19d08672015-01-27 18:47:05 +00004489 //
4490 // C++14 [over.ics.list]p3:
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00004491 // Otherwise, if the parameter type is "array of N X", if the initializer
Larisse Voufo19d08672015-01-27 18:47:05 +00004492 // list has exactly N elements or if it has fewer than N elements and X is
4493 // default-constructible, and if all the elements of the initializer list
4494 // can be implicitly converted to X, the implicit conversion sequence is
4495 // the worst conversion necessary to convert an element of the list to X.
Richard Smith1bbaba82015-01-27 23:23:39 +00004496 //
4497 // FIXME: We're missing a lot of these checks.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004498 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004499 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004500 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004501 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004502 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004503 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004504 if (!X.isNull()) {
4505 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4506 Expr *Init = From->getInit(i);
4507 ImplicitConversionSequence ICS =
4508 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4509 InOverloadResolution,
4510 AllowObjCWritebackConversion);
4511 // If a single element isn't convertible, fail.
4512 if (ICS.isBad()) {
4513 Result = ICS;
4514 break;
4515 }
4516 // Otherwise, look for the worst conversion.
4517 if (Result.isBad() ||
4518 CompareImplicitConversionSequences(S, ICS, Result) ==
4519 ImplicitConversionSequence::Worse)
4520 Result = ICS;
4521 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004522
4523 // For an empty list, we won't have computed any conversion sequence.
4524 // Introduce the identity conversion sequence.
4525 if (From->getNumInits() == 0) {
4526 Result.setStandard();
4527 Result.Standard.setAsIdentityConversion();
4528 Result.Standard.setFromType(ToType);
4529 Result.Standard.setAllToTypes(ToType);
4530 }
4531
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004532 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004533 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004534 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004535
Larisse Voufo19d08672015-01-27 18:47:05 +00004536 // C++14 [over.ics.list]p4:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004537 // C++11 [over.ics.list]p3:
4538 // Otherwise, if the parameter is a non-aggregate class X and overload
4539 // resolution chooses a single best constructor [...] the implicit
4540 // conversion sequence is a user-defined conversion sequence. If multiple
4541 // constructors are viable but none is better than the others, the
4542 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004543 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4544 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004545 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4546 /*AllowExplicit=*/false,
4547 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004548 AllowObjCWritebackConversion,
4549 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004550 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004551
Larisse Voufo19d08672015-01-27 18:47:05 +00004552 // C++14 [over.ics.list]p5:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004553 // C++11 [over.ics.list]p4:
4554 // Otherwise, if the parameter has an aggregate type which can be
4555 // initialized from the initializer list [...] the implicit conversion
4556 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004557 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004558 // Type is an aggregate, argument is an init list. At this point it comes
4559 // down to checking whether the initialization works.
4560 // FIXME: Find out whether this parameter is consumed or not.
4561 InitializedEntity Entity =
4562 InitializedEntity::InitializeParameter(S.Context, ToType,
4563 /*Consumed=*/false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004564 if (S.CanPerformCopyInitialization(Entity, From)) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004565 Result.setUserDefined();
4566 Result.UserDefined.Before.setAsIdentityConversion();
4567 // Initializer lists don't have a type.
4568 Result.UserDefined.Before.setFromType(QualType());
4569 Result.UserDefined.Before.setAllToTypes(QualType());
4570
4571 Result.UserDefined.After.setAsIdentityConversion();
4572 Result.UserDefined.After.setFromType(ToType);
4573 Result.UserDefined.After.setAllToTypes(ToType);
Craig Topperc3ec1492014-05-26 06:22:03 +00004574 Result.UserDefined.ConversionFunction = nullptr;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004575 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004576 return Result;
4577 }
4578
Larisse Voufo19d08672015-01-27 18:47:05 +00004579 // C++14 [over.ics.list]p6:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004580 // C++11 [over.ics.list]p5:
4581 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004582 if (ToType->isReferenceType()) {
4583 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4584 // mention initializer lists in any way. So we go by what list-
4585 // initialization would do and try to extrapolate from that.
4586
4587 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4588
4589 // If the initializer list has a single element that is reference-related
4590 // to the parameter type, we initialize the reference from that.
4591 if (From->getNumInits() == 1) {
4592 Expr *Init = From->getInit(0);
4593
4594 QualType T2 = Init->getType();
4595
4596 // If the initializer is the address of an overloaded function, try
4597 // to resolve the overloaded function. If all goes well, T2 is the
4598 // type of the resulting function.
4599 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4600 DeclAccessPair Found;
4601 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4602 Init, ToType, false, Found))
4603 T2 = Fn->getType();
4604 }
4605
4606 // Compute some basic properties of the types and the initializer.
4607 bool dummy1 = false;
4608 bool dummy2 = false;
4609 bool dummy3 = false;
4610 Sema::ReferenceCompareResult RefRelationship
4611 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4612 dummy2, dummy3);
4613
Richard Smith4d2bbd72013-09-06 01:22:42 +00004614 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004615 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4616 SuppressUserConversions,
4617 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004618 }
Sebastian Redldf888642011-12-03 14:54:30 +00004619 }
4620
4621 // Otherwise, we bind the reference to a temporary created from the
4622 // initializer list.
4623 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4624 InOverloadResolution,
4625 AllowObjCWritebackConversion);
4626 if (Result.isFailure())
4627 return Result;
4628 assert(!Result.isEllipsis() &&
4629 "Sub-initialization cannot result in ellipsis conversion.");
4630
4631 // Can we even bind to a temporary?
4632 if (ToType->isRValueReferenceType() ||
4633 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4634 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4635 Result.UserDefined.After;
4636 SCS.ReferenceBinding = true;
4637 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4638 SCS.BindsToRvalue = true;
4639 SCS.BindsToFunctionLvalue = false;
4640 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4641 SCS.ObjCLifetimeConversionBinding = false;
4642 } else
4643 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4644 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004645 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004646 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004647
Larisse Voufo19d08672015-01-27 18:47:05 +00004648 // C++14 [over.ics.list]p7:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004649 // C++11 [over.ics.list]p6:
4650 // Otherwise, if the parameter type is not a class:
4651 if (!ToType->isRecordType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004652 // - if the initializer list has one element that is not itself an
4653 // initializer list, the implicit conversion sequence is the one
4654 // required to convert the element to the parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004655 unsigned NumInits = From->getNumInits();
Richard Smith1bbaba82015-01-27 23:23:39 +00004656 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004657 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4658 SuppressUserConversions,
4659 InOverloadResolution,
4660 AllowObjCWritebackConversion);
4661 // - if the initializer list has no elements, the implicit conversion
4662 // sequence is the identity conversion.
4663 else if (NumInits == 0) {
4664 Result.setStandard();
4665 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004666 Result.Standard.setFromType(ToType);
4667 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004668 }
4669 return Result;
4670 }
4671
Larisse Voufo19d08672015-01-27 18:47:05 +00004672 // C++14 [over.ics.list]p8:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004673 // C++11 [over.ics.list]p7:
4674 // In all cases other than those enumerated above, no conversion is possible
4675 return Result;
4676}
4677
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004678/// TryCopyInitialization - Try to copy-initialize a value of type
4679/// ToType from the expression From. Return the implicit conversion
4680/// sequence required to pass this argument, which may be a bad
4681/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004682/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004683/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004684static ImplicitConversionSequence
4685TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004686 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004687 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004688 bool AllowObjCWritebackConversion,
4689 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004690 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4691 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4692 InOverloadResolution,AllowObjCWritebackConversion);
4693
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004694 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004695 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004696 /*FIXME:*/From->getLocStart(),
4697 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004698 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004699
John McCall5c32be02010-08-24 20:38:10 +00004700 return TryImplicitConversion(S, From, ToType,
4701 SuppressUserConversions,
4702 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004703 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004704 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004705 AllowObjCWritebackConversion,
4706 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004707}
4708
Anna Zaks1b068122011-07-28 19:46:48 +00004709static bool TryCopyInitialization(const CanQualType FromQTy,
4710 const CanQualType ToQTy,
4711 Sema &S,
4712 SourceLocation Loc,
4713 ExprValueKind FromVK) {
4714 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4715 ImplicitConversionSequence ICS =
4716 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4717
4718 return !ICS.isBad();
4719}
4720
Douglas Gregor436424c2008-11-18 23:14:02 +00004721/// TryObjectArgumentInitialization - Try to initialize the object
4722/// parameter of the given member function (@c Method) from the
4723/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004724static ImplicitConversionSequence
Richard Smith03c66d32013-01-26 02:07:32 +00004725TryObjectArgumentInitialization(Sema &S, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004726 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004727 CXXMethodDecl *Method,
4728 CXXRecordDecl *ActingContext) {
4729 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004730 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4731 // const volatile object.
4732 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4733 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004734 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004735
4736 // Set up the conversion sequence as a "bad" conversion, to allow us
4737 // to exit early.
4738 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004739
4740 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00004741 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004742 FromType = PT->getPointeeType();
4743
Douglas Gregor02824322011-01-26 19:30:28 +00004744 // When we had a pointer, it's implicitly dereferenced, so we
4745 // better have an lvalue.
4746 assert(FromClassification.isLValue());
4747 }
4748
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004749 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004750
Douglas Gregor02824322011-01-26 19:30:28 +00004751 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004752 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004753 // parameter is
4754 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004755 // - "lvalue reference to cv X" for functions declared without a
4756 // ref-qualifier or with the & ref-qualifier
4757 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004758 // ref-qualifier
4759 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004760 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004761 // cv-qualification on the member function declaration.
4762 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004763 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004764 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004765 // (C++ [over.match.funcs]p5). We perform a simplified version of
4766 // reference binding here, that allows class rvalues to bind to
4767 // non-constant references.
4768
Douglas Gregor02824322011-01-26 19:30:28 +00004769 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004770 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004771 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004772 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004773 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004774 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00004775 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004776 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004777 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004778
4779 // Check that we have either the same type or a derived type. It
4780 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004781 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004782 ImplicitConversionKind SecondKind;
4783 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4784 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004785 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004786 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004787 else {
John McCall65eb8792010-02-25 01:37:24 +00004788 ICS.setBad(BadConversionSequence::unrelated_class,
4789 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004790 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004791 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004792
Douglas Gregor02824322011-01-26 19:30:28 +00004793 // Check the ref-qualifier.
4794 switch (Method->getRefQualifier()) {
4795 case RQ_None:
4796 // Do nothing; we don't care about lvalueness or rvalueness.
4797 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004798
Douglas Gregor02824322011-01-26 19:30:28 +00004799 case RQ_LValue:
4800 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4801 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004802 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004803 ImplicitParamType);
4804 return ICS;
4805 }
4806 break;
4807
4808 case RQ_RValue:
4809 if (!FromClassification.isRValue()) {
4810 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004811 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004812 ImplicitParamType);
4813 return ICS;
4814 }
4815 break;
4816 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004817
Douglas Gregor436424c2008-11-18 23:14:02 +00004818 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004819 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004820 ICS.Standard.setAsIdentityConversion();
4821 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004822 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004823 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004824 ICS.Standard.ReferenceBinding = true;
4825 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004826 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004827 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004828 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4829 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4830 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004831 return ICS;
4832}
4833
4834/// PerformObjectArgumentInitialization - Perform initialization of
4835/// the implicit object parameter for the given Method with the given
4836/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004837ExprResult
4838Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004839 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004840 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004841 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004842 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004843 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004844 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004845
Douglas Gregor02824322011-01-26 19:30:28 +00004846 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004847 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004848 FromRecordType = PT->getPointeeType();
4849 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004850 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004851 } else {
4852 FromRecordType = From->getType();
4853 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004854 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004855 }
4856
John McCall6e9f8f62009-12-03 04:06:58 +00004857 // Note that we always use the true parent context when performing
4858 // the actual argument initialization.
Nico Weberb58e51c2014-11-19 05:21:39 +00004859 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
4860 *this, From->getType(), FromClassification, Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004861 if (ICS.isBad()) {
4862 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4863 Qualifiers FromQs = FromRecordType.getQualifiers();
4864 Qualifiers ToQs = DestType.getQualifiers();
4865 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4866 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004867 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004868 diag::err_member_function_call_bad_cvr)
4869 << Method->getDeclName() << FromRecordType << (CVR - 1)
4870 << From->getSourceRange();
4871 Diag(Method->getLocation(), diag::note_previous_decl)
4872 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004873 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004874 }
4875 }
4876
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004877 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004878 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004879 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004880 }
Mike Stump11289f42009-09-09 15:08:12 +00004881
John Wiegley01296292011-04-08 18:41:53 +00004882 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4883 ExprResult FromRes =
4884 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4885 if (FromRes.isInvalid())
4886 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004887 From = FromRes.get();
John Wiegley01296292011-04-08 18:41:53 +00004888 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004889
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004890 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004891 From = ImpCastExprToType(From, DestType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004892 From->getValueKind()).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004893 return From;
Douglas Gregor436424c2008-11-18 23:14:02 +00004894}
4895
Douglas Gregor5fb53972009-01-14 15:45:31 +00004896/// TryContextuallyConvertToBool - Attempt to contextually convert the
4897/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004898static ImplicitConversionSequence
4899TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00004900 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004901 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004902 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004903 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004904 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004905 /*AllowObjCWritebackConversion=*/false,
4906 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004907}
4908
4909/// PerformContextuallyConvertToBool - Perform a contextual conversion
4910/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004911ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004912 if (checkPlaceholderForOverload(*this, From))
4913 return ExprError();
4914
John McCall5c32be02010-08-24 20:38:10 +00004915 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004916 if (!ICS.isBad())
4917 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004918
Fariborz Jahanian76197412009-11-18 18:26:29 +00004919 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004920 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00004921 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004922 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004923 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004924}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004925
Richard Smithf8379a02012-01-18 23:55:52 +00004926/// Check that the specified conversion is permitted in a converted constant
4927/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4928/// is acceptable.
4929static bool CheckConvertedConstantConversions(Sema &S,
4930 StandardConversionSequence &SCS) {
4931 // Since we know that the target type is an integral or unscoped enumeration
4932 // type, most conversion kinds are impossible. All possible First and Third
4933 // conversions are fine.
4934 switch (SCS.Second) {
4935 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00004936 case ICK_NoReturn_Adjustment:
Richard Smithf8379a02012-01-18 23:55:52 +00004937 case ICK_Integral_Promotion:
Richard Smith410cc892014-11-26 03:26:53 +00004938 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
Richard Smithf8379a02012-01-18 23:55:52 +00004939 return true;
4940
4941 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00004942 // Conversion from an integral or unscoped enumeration type to bool is
Richard Smith410cc892014-11-26 03:26:53 +00004943 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
4944 // conversion, so we allow it in a converted constant expression.
4945 //
4946 // FIXME: Per core issue 1407, we should not allow this, but that breaks
4947 // a lot of popular code. We should at least add a warning for this
4948 // (non-conforming) extension.
Richard Smithca24ed42012-09-13 22:00:12 +00004949 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4950 SCS.getToType(2)->isBooleanType();
4951
Richard Smith410cc892014-11-26 03:26:53 +00004952 case ICK_Pointer_Conversion:
4953 case ICK_Pointer_Member:
4954 // C++1z: null pointer conversions and null member pointer conversions are
4955 // only permitted if the source type is std::nullptr_t.
4956 return SCS.getFromType()->isNullPtrType();
4957
4958 case ICK_Floating_Promotion:
4959 case ICK_Complex_Promotion:
4960 case ICK_Floating_Conversion:
4961 case ICK_Complex_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00004962 case ICK_Floating_Integral:
Richard Smith410cc892014-11-26 03:26:53 +00004963 case ICK_Compatible_Conversion:
4964 case ICK_Derived_To_Base:
4965 case ICK_Vector_Conversion:
4966 case ICK_Vector_Splat:
Richard Smithf8379a02012-01-18 23:55:52 +00004967 case ICK_Complex_Real:
Richard Smith410cc892014-11-26 03:26:53 +00004968 case ICK_Block_Pointer_Conversion:
4969 case ICK_TransparentUnionConversion:
4970 case ICK_Writeback_Conversion:
4971 case ICK_Zero_Event_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00004972 return false;
4973
4974 case ICK_Lvalue_To_Rvalue:
4975 case ICK_Array_To_Pointer:
4976 case ICK_Function_To_Pointer:
Richard Smith410cc892014-11-26 03:26:53 +00004977 llvm_unreachable("found a first conversion kind in Second");
4978
Richard Smithf8379a02012-01-18 23:55:52 +00004979 case ICK_Qualification:
Richard Smith410cc892014-11-26 03:26:53 +00004980 llvm_unreachable("found a third conversion kind in Second");
Richard Smithf8379a02012-01-18 23:55:52 +00004981
4982 case ICK_Num_Conversion_Kinds:
4983 break;
4984 }
4985
4986 llvm_unreachable("unknown conversion kind");
4987}
4988
4989/// CheckConvertedConstantExpression - Check that the expression From is a
4990/// converted constant expression of type T, perform the conversion and produce
4991/// the converted expression, per C++11 [expr.const]p3.
Richard Smith410cc892014-11-26 03:26:53 +00004992static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
4993 QualType T, APValue &Value,
4994 Sema::CCEKind CCE,
4995 bool RequireInt) {
4996 assert(S.getLangOpts().CPlusPlus11 &&
4997 "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00004998
Richard Smith410cc892014-11-26 03:26:53 +00004999 if (checkPlaceholderForOverload(S, From))
Richard Smithf8379a02012-01-18 23:55:52 +00005000 return ExprError();
5001
Richard Smith410cc892014-11-26 03:26:53 +00005002 // C++1z [expr.const]p3:
5003 // A converted constant expression of type T is an expression,
5004 // implicitly converted to type T, where the converted
5005 // expression is a constant expression and the implicit conversion
5006 // sequence contains only [... list of conversions ...].
Richard Smithf8379a02012-01-18 23:55:52 +00005007 ImplicitConversionSequence ICS =
Richard Smith410cc892014-11-26 03:26:53 +00005008 TryCopyInitialization(S, From, T,
Richard Smithf8379a02012-01-18 23:55:52 +00005009 /*SuppressUserConversions=*/false,
Richard Smithf8379a02012-01-18 23:55:52 +00005010 /*InOverloadResolution=*/false,
Richard Smith410cc892014-11-26 03:26:53 +00005011 /*AllowObjcWritebackConversion=*/false,
5012 /*AllowExplicit=*/false);
Craig Topperc3ec1492014-05-26 06:22:03 +00005013 StandardConversionSequence *SCS = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +00005014 switch (ICS.getKind()) {
5015 case ImplicitConversionSequence::StandardConversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005016 SCS = &ICS.Standard;
5017 break;
5018 case ImplicitConversionSequence::UserDefinedConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005019 // We are converting to a non-class type, so the Before sequence
5020 // must be trivial.
Richard Smithf8379a02012-01-18 23:55:52 +00005021 SCS = &ICS.UserDefined.After;
5022 break;
5023 case ImplicitConversionSequence::AmbiguousConversion:
5024 case ImplicitConversionSequence::BadConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005025 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5026 return S.Diag(From->getLocStart(),
5027 diag::err_typecheck_converted_constant_expression)
5028 << From->getType() << From->getSourceRange() << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005029 return ExprError();
5030
5031 case ImplicitConversionSequence::EllipsisConversion:
5032 llvm_unreachable("ellipsis conversion in converted constant expression");
5033 }
5034
Richard Smith410cc892014-11-26 03:26:53 +00005035 // Check that we would only use permitted conversions.
5036 if (!CheckConvertedConstantConversions(S, *SCS)) {
5037 return S.Diag(From->getLocStart(),
5038 diag::err_typecheck_converted_constant_expression_disallowed)
5039 << From->getType() << From->getSourceRange() << T;
5040 }
5041 // [...] and where the reference binding (if any) binds directly.
5042 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5043 return S.Diag(From->getLocStart(),
5044 diag::err_typecheck_converted_constant_expression_indirect)
5045 << From->getType() << From->getSourceRange() << T;
5046 }
5047
5048 ExprResult Result =
5049 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
Richard Smithf8379a02012-01-18 23:55:52 +00005050 if (Result.isInvalid())
5051 return Result;
5052
5053 // Check for a narrowing implicit conversion.
5054 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005055 QualType PreNarrowingType;
Richard Smith410cc892014-11-26 03:26:53 +00005056 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
Richard Smith5614ca72012-03-23 23:55:39 +00005057 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00005058 case NK_Variable_Narrowing:
5059 // Implicit conversion to a narrower type, and the value is not a constant
5060 // expression. We'll diagnose this in a moment.
5061 case NK_Not_Narrowing:
5062 break;
5063
5064 case NK_Constant_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005065 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005066 << CCE << /*Constant*/1
Richard Smith410cc892014-11-26 03:26:53 +00005067 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005068 break;
5069
5070 case NK_Type_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005071 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005072 << CCE << /*Constant*/0 << From->getType() << T;
5073 break;
5074 }
5075
5076 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005077 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005078 Expr::EvalResult Eval;
5079 Eval.Diag = &Notes;
5080
Richard Smith410cc892014-11-26 03:26:53 +00005081 if ((T->isReferenceType()
5082 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5083 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5084 (RequireInt && !Eval.Val.isInt())) {
Richard Smithf8379a02012-01-18 23:55:52 +00005085 // The expression can't be folded, so we can't keep it at this position in
5086 // the AST.
5087 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005088 } else {
Richard Smith410cc892014-11-26 03:26:53 +00005089 Value = Eval.Val;
Richard Smith911e1422012-01-30 22:27:01 +00005090
5091 if (Notes.empty()) {
5092 // It's a constant expression.
5093 return Result;
5094 }
Richard Smithf8379a02012-01-18 23:55:52 +00005095 }
5096
5097 // It's not a constant expression. Produce an appropriate diagnostic.
5098 if (Notes.size() == 1 &&
5099 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
Richard Smith410cc892014-11-26 03:26:53 +00005100 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
Richard Smithf8379a02012-01-18 23:55:52 +00005101 else {
Richard Smith410cc892014-11-26 03:26:53 +00005102 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005103 << CCE << From->getSourceRange();
5104 for (unsigned I = 0; I < Notes.size(); ++I)
Richard Smith410cc892014-11-26 03:26:53 +00005105 S.Diag(Notes[I].first, Notes[I].second);
Richard Smithf8379a02012-01-18 23:55:52 +00005106 }
Richard Smith410cc892014-11-26 03:26:53 +00005107 return ExprError();
Richard Smithf8379a02012-01-18 23:55:52 +00005108}
5109
Richard Smith410cc892014-11-26 03:26:53 +00005110ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5111 APValue &Value, CCEKind CCE) {
5112 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5113}
5114
5115ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5116 llvm::APSInt &Value,
5117 CCEKind CCE) {
5118 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5119
5120 APValue V;
5121 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5122 if (!R.isInvalid())
5123 Value = V.getInt();
5124 return R;
5125}
5126
5127
John McCallfec112d2011-09-09 06:11:02 +00005128/// dropPointerConversions - If the given standard conversion sequence
5129/// involves any pointer conversions, remove them. This may change
5130/// the result type of the conversion sequence.
5131static void dropPointerConversion(StandardConversionSequence &SCS) {
5132 if (SCS.Second == ICK_Pointer_Conversion) {
5133 SCS.Second = ICK_Identity;
5134 SCS.Third = ICK_Identity;
5135 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5136 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005137}
John McCall5c32be02010-08-24 20:38:10 +00005138
John McCallfec112d2011-09-09 06:11:02 +00005139/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5140/// convert the expression From to an Objective-C pointer type.
5141static ImplicitConversionSequence
5142TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5143 // Do an implicit conversion to 'id'.
5144 QualType Ty = S.Context.getObjCIdType();
5145 ImplicitConversionSequence ICS
5146 = TryImplicitConversion(S, From, Ty,
5147 // FIXME: Are these flags correct?
5148 /*SuppressUserConversions=*/false,
5149 /*AllowExplicit=*/true,
5150 /*InOverloadResolution=*/false,
5151 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005152 /*AllowObjCWritebackConversion=*/false,
5153 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005154
5155 // Strip off any final conversions to 'id'.
5156 switch (ICS.getKind()) {
5157 case ImplicitConversionSequence::BadConversion:
5158 case ImplicitConversionSequence::AmbiguousConversion:
5159 case ImplicitConversionSequence::EllipsisConversion:
5160 break;
5161
5162 case ImplicitConversionSequence::UserDefinedConversion:
5163 dropPointerConversion(ICS.UserDefined.After);
5164 break;
5165
5166 case ImplicitConversionSequence::StandardConversion:
5167 dropPointerConversion(ICS.Standard);
5168 break;
5169 }
5170
5171 return ICS;
5172}
5173
5174/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5175/// conversion of the expression From to an Objective-C pointer type.
5176ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005177 if (checkPlaceholderForOverload(*this, From))
5178 return ExprError();
5179
John McCall8b07ec22010-05-15 11:32:37 +00005180 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005181 ImplicitConversionSequence ICS =
5182 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005183 if (!ICS.isBad())
5184 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005185 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005186}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005187
Richard Smith8dd34252012-02-04 07:07:42 +00005188/// Determine whether the provided type is an integral type, or an enumeration
5189/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005190bool Sema::ICEConvertDiagnoser::match(QualType T) {
5191 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5192 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005193}
5194
Larisse Voufo236bec22013-06-10 06:50:24 +00005195static ExprResult
5196diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5197 Sema::ContextualImplicitConverter &Converter,
5198 QualType T, UnresolvedSetImpl &ViableConversions) {
5199
5200 if (Converter.Suppress)
5201 return ExprError();
5202
5203 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5204 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5205 CXXConversionDecl *Conv =
5206 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5207 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5208 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5209 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005210 return From;
Larisse Voufo236bec22013-06-10 06:50:24 +00005211}
5212
5213static bool
5214diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5215 Sema::ContextualImplicitConverter &Converter,
5216 QualType T, bool HadMultipleCandidates,
5217 UnresolvedSetImpl &ExplicitConversions) {
5218 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5219 DeclAccessPair Found = ExplicitConversions[0];
5220 CXXConversionDecl *Conversion =
5221 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5222
5223 // The user probably meant to invoke the given explicit
5224 // conversion; use it.
5225 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5226 std::string TypeStr;
5227 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5228
5229 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5230 << FixItHint::CreateInsertion(From->getLocStart(),
5231 "static_cast<" + TypeStr + ">(")
5232 << FixItHint::CreateInsertion(
Alp Tokerb6cc5922014-05-03 03:45:55 +00005233 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
Larisse Voufo236bec22013-06-10 06:50:24 +00005234 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5235
5236 // If we aren't in a SFINAE context, build a call to the
5237 // explicit conversion function.
5238 if (SemaRef.isSFINAEContext())
5239 return true;
5240
Craig Topperc3ec1492014-05-26 06:22:03 +00005241 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005242 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5243 HadMultipleCandidates);
5244 if (Result.isInvalid())
5245 return true;
5246 // Record usage of conversion in an implicit cast.
5247 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005248 CK_UserDefinedConversion, Result.get(),
5249 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005250 }
5251 return false;
5252}
5253
5254static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5255 Sema::ContextualImplicitConverter &Converter,
5256 QualType T, bool HadMultipleCandidates,
5257 DeclAccessPair &Found) {
5258 CXXConversionDecl *Conversion =
5259 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005260 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005261
5262 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5263 if (!Converter.SuppressConversion) {
5264 if (SemaRef.isSFINAEContext())
5265 return true;
5266
5267 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5268 << From->getSourceRange();
5269 }
5270
5271 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5272 HadMultipleCandidates);
5273 if (Result.isInvalid())
5274 return true;
5275 // Record usage of conversion in an implicit cast.
5276 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005277 CK_UserDefinedConversion, Result.get(),
5278 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005279 return false;
5280}
5281
5282static ExprResult finishContextualImplicitConversion(
5283 Sema &SemaRef, SourceLocation Loc, Expr *From,
5284 Sema::ContextualImplicitConverter &Converter) {
5285 if (!Converter.match(From->getType()) && !Converter.Suppress)
5286 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5287 << From->getSourceRange();
5288
5289 return SemaRef.DefaultLvalueConversion(From);
5290}
5291
5292static void
5293collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5294 UnresolvedSetImpl &ViableConversions,
5295 OverloadCandidateSet &CandidateSet) {
5296 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5297 DeclAccessPair FoundDecl = ViableConversions[I];
5298 NamedDecl *D = FoundDecl.getDecl();
5299 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5300 if (isa<UsingShadowDecl>(D))
5301 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5302
5303 CXXConversionDecl *Conv;
5304 FunctionTemplateDecl *ConvTemplate;
5305 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5306 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5307 else
5308 Conv = cast<CXXConversionDecl>(D);
5309
5310 if (ConvTemplate)
5311 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005312 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5313 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005314 else
5315 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005316 ToType, CandidateSet,
5317 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005318 }
5319}
5320
Richard Smithccc11812013-05-21 19:05:48 +00005321/// \brief Attempt to convert the given expression to a type which is accepted
5322/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005323///
Richard Smithccc11812013-05-21 19:05:48 +00005324/// This routine will attempt to convert an expression of class type to a
5325/// type accepted by the specified converter. In C++11 and before, the class
5326/// must have a single non-explicit conversion function converting to a matching
5327/// type. In C++1y, there can be multiple such conversion functions, but only
5328/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005329///
Douglas Gregor4799d032010-06-30 00:20:43 +00005330/// \param Loc The source location of the construct that requires the
5331/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005332///
James Dennett18348b62012-06-22 08:52:37 +00005333/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005334///
Richard Smithccc11812013-05-21 19:05:48 +00005335/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005336///
Douglas Gregor4799d032010-06-30 00:20:43 +00005337/// \returns The expression, converted to an integral or enumeration type if
5338/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005339ExprResult Sema::PerformContextualImplicitConversion(
5340 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005341 // We can't perform any more checking for type-dependent expressions.
5342 if (From->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005343 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005344
Eli Friedman1da70392012-01-26 00:26:18 +00005345 // Process placeholders immediately.
5346 if (From->hasPlaceholderType()) {
5347 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005348 if (result.isInvalid())
5349 return result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005350 From = result.get();
Eli Friedman1da70392012-01-26 00:26:18 +00005351 }
5352
Richard Smithccc11812013-05-21 19:05:48 +00005353 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005354 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005355 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005356 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005357
5358 // FIXME: Check for missing '()' if T is a function type?
5359
Richard Smithccc11812013-05-21 19:05:48 +00005360 // We can only perform contextual implicit conversions on objects of class
5361 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005362 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005363 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005364 if (!Converter.Suppress)
5365 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005366 return From;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005367 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005368
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005369 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005370 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005371 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005372 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005373
5374 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5375 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5376
Craig Toppere14c0f82014-03-12 04:55:44 +00005377 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00005378 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005379 }
Richard Smithccc11812013-05-21 19:05:48 +00005380 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005381
5382 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005383 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005384
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005385 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005386 UnresolvedSet<4>
5387 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005388 UnresolvedSet<4> ExplicitConversions;
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005389 const auto &Conversions =
Larisse Voufo236bec22013-06-10 06:50:24 +00005390 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005391
Larisse Voufo236bec22013-06-10 06:50:24 +00005392 bool HadMultipleCandidates =
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005393 (std::distance(Conversions.begin(), Conversions.end()) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005394
Larisse Voufo236bec22013-06-10 06:50:24 +00005395 // To check that there is only one target type, in C++1y:
5396 QualType ToType;
5397 bool HasUniqueTargetType = true;
5398
5399 // Collect explicit or viable (potentially in C++1y) conversions.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005400 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005401 NamedDecl *D = (*I)->getUnderlyingDecl();
5402 CXXConversionDecl *Conversion;
5403 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5404 if (ConvTemplate) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005405 if (getLangOpts().CPlusPlus14)
Larisse Voufo236bec22013-06-10 06:50:24 +00005406 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5407 else
5408 continue; // C++11 does not consider conversion operator templates(?).
5409 } else
5410 Conversion = cast<CXXConversionDecl>(D);
5411
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005412 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
Larisse Voufo236bec22013-06-10 06:50:24 +00005413 "Conversion operator templates are considered potentially "
5414 "viable in C++1y");
5415
5416 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5417 if (Converter.match(CurToType) || ConvTemplate) {
5418
5419 if (Conversion->isExplicit()) {
5420 // FIXME: For C++1y, do we need this restriction?
5421 // cf. diagnoseNoViableConversion()
5422 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005423 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005424 } else {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005425 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005426 if (ToType.isNull())
5427 ToType = CurToType.getUnqualifiedType();
5428 else if (HasUniqueTargetType &&
5429 (CurToType.getUnqualifiedType() != ToType))
5430 HasUniqueTargetType = false;
5431 }
5432 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005433 }
Richard Smith8dd34252012-02-04 07:07:42 +00005434 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005435 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005436
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005437 if (getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005438 // C++1y [conv]p6:
5439 // ... An expression e of class type E appearing in such a context
5440 // is said to be contextually implicitly converted to a specified
5441 // type T and is well-formed if and only if e can be implicitly
5442 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005443 // for conversion functions whose return type is cv T or reference to
5444 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005445 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005446
Larisse Voufo236bec22013-06-10 06:50:24 +00005447 // If no unique T is found:
5448 if (ToType.isNull()) {
5449 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5450 HadMultipleCandidates,
5451 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005452 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005453 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005454 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005455
Larisse Voufo236bec22013-06-10 06:50:24 +00005456 // If more than one unique Ts are found:
5457 if (!HasUniqueTargetType)
5458 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5459 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005460
Larisse Voufo236bec22013-06-10 06:50:24 +00005461 // If one unique T is found:
5462 // First, build a candidate set from the previously recorded
5463 // potentially viable conversions.
Richard Smith100b24a2014-04-17 01:52:14 +00005464 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo236bec22013-06-10 06:50:24 +00005465 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5466 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005467
Larisse Voufo236bec22013-06-10 06:50:24 +00005468 // Then, perform overload resolution over the candidate set.
5469 OverloadCandidateSet::iterator Best;
5470 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5471 case OR_Success: {
5472 // Apply this conversion.
5473 DeclAccessPair Found =
5474 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5475 if (recordConversion(*this, Loc, From, Converter, T,
5476 HadMultipleCandidates, Found))
5477 return ExprError();
5478 break;
5479 }
5480 case OR_Ambiguous:
5481 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5482 ViableConversions);
5483 case OR_No_Viable_Function:
5484 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5485 HadMultipleCandidates,
5486 ExplicitConversions))
5487 return ExprError();
5488 // fall through 'OR_Deleted' case.
5489 case OR_Deleted:
5490 // We'll complain below about a non-integral condition type.
5491 break;
5492 }
5493 } else {
5494 switch (ViableConversions.size()) {
5495 case 0: {
5496 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5497 HadMultipleCandidates,
5498 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005499 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005500
Larisse Voufo236bec22013-06-10 06:50:24 +00005501 // We'll complain below about a non-integral condition type.
5502 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005503 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005504 case 1: {
5505 // Apply this conversion.
5506 DeclAccessPair Found = ViableConversions[0];
5507 if (recordConversion(*this, Loc, From, Converter, T,
5508 HadMultipleCandidates, Found))
5509 return ExprError();
5510 break;
5511 }
5512 default:
5513 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5514 ViableConversions);
5515 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005516 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005517
Larisse Voufo236bec22013-06-10 06:50:24 +00005518 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005519}
5520
Richard Smith100b24a2014-04-17 01:52:14 +00005521/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5522/// an acceptable non-member overloaded operator for a call whose
5523/// arguments have types T1 (and, if non-empty, T2). This routine
5524/// implements the check in C++ [over.match.oper]p3b2 concerning
5525/// enumeration types.
5526static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5527 FunctionDecl *Fn,
5528 ArrayRef<Expr *> Args) {
5529 QualType T1 = Args[0]->getType();
5530 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5531
5532 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5533 return true;
5534
5535 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5536 return true;
5537
5538 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5539 if (Proto->getNumParams() < 1)
5540 return false;
5541
5542 if (T1->isEnumeralType()) {
5543 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5544 if (Context.hasSameUnqualifiedType(T1, ArgType))
5545 return true;
5546 }
5547
5548 if (Proto->getNumParams() < 2)
5549 return false;
5550
5551 if (!T2.isNull() && T2->isEnumeralType()) {
5552 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5553 if (Context.hasSameUnqualifiedType(T2, ArgType))
5554 return true;
5555 }
5556
5557 return false;
5558}
5559
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005560/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005561/// candidate functions, using the given function call arguments. If
5562/// @p SuppressUserConversions, then don't allow user-defined
5563/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005564///
James Dennett2a4d13c2012-06-15 07:13:21 +00005565/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005566/// based on an incomplete set of function arguments. This feature is used by
5567/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005568void
5569Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005570 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005571 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005572 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005573 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005574 bool PartialOverloading,
5575 bool AllowExplicit) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005576 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005577 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005578 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005579 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005580 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005581
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005582 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005583 if (!isa<CXXConstructorDecl>(Method)) {
5584 // If we get here, it's because we're calling a member function
5585 // that is named without a member access expression (e.g.,
5586 // "this->f") that was either written explicitly or created
5587 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005588 // function, e.g., X::f(). We use an empty type for the implied
5589 // object argument (C++ [over.call.func]p3), and the acting context
5590 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005591 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005592 QualType(), Expr::Classification::makeSimpleLValue(),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005593 Args, CandidateSet, SuppressUserConversions,
5594 PartialOverloading);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005595 return;
5596 }
5597 // We treat a constructor like a non-member function, since its object
5598 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005599 }
5600
Douglas Gregorff7028a2009-11-13 23:59:09 +00005601 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005602 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005603
Richard Smith100b24a2014-04-17 01:52:14 +00005604 // C++ [over.match.oper]p3:
5605 // if no operand has a class type, only those non-member functions in the
5606 // lookup set that have a first parameter of type T1 or "reference to
5607 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5608 // is a right operand) a second parameter of type T2 or "reference to
5609 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5610 // candidate functions.
5611 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5612 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5613 return;
5614
Richard Smith8b86f2d2013-11-04 01:48:18 +00005615 // C++11 [class.copy]p11: [DR1402]
5616 // A defaulted move constructor that is defined as deleted is ignored by
5617 // overload resolution.
5618 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5619 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5620 Constructor->isMoveConstructor())
5621 return;
5622
Douglas Gregor27381f32009-11-23 12:27:39 +00005623 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005624 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005625
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005626 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005627 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005628 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005629 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005630 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005631 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005632 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005633 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005634
John McCall578a1f82014-12-14 01:46:53 +00005635 if (Constructor) {
5636 // C++ [class.copy]p3:
5637 // A member function template is never instantiated to perform the copy
5638 // of a class object to an object of its class type.
5639 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5640 if (Args.size() == 1 &&
5641 Constructor->isSpecializationCopyingObject() &&
5642 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5643 IsDerivedFrom(Args[0]->getType(), ClassType))) {
5644 Candidate.Viable = false;
5645 Candidate.FailureKind = ovl_fail_illegal_constructor;
5646 return;
5647 }
5648 }
5649
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005650 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005651
5652 // (C++ 13.3.2p2): A candidate function having fewer than m
5653 // parameters is viable only if it has an ellipsis in its parameter
5654 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005655 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005656 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005657 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005658 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005659 return;
5660 }
5661
5662 // (C++ 13.3.2p2): A candidate function having more than m parameters
5663 // is viable only if the (m+1)st parameter has a default argument
5664 // (8.3.6). For the purposes of overload resolution, the
5665 // parameter list is truncated on the right, so that there are
5666 // exactly m parameters.
5667 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005668 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005669 // Not enough arguments.
5670 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005671 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005672 return;
5673 }
5674
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005675 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005676 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005677 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005678 // Skip the check for callers that are implicit members, because in this
5679 // case we may not yet know what the member's target is; the target is
5680 // inferred for the member automatically, based on the bases and fields of
5681 // the class.
5682 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005683 Candidate.Viable = false;
5684 Candidate.FailureKind = ovl_fail_bad_target;
5685 return;
5686 }
5687
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005688 // Determine the implicit conversion sequences for each of the
5689 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005690 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005691 if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005692 // (C++ 13.3.2p3): for F to be a viable function, there shall
5693 // exist for each argument an implicit conversion sequence
5694 // (13.3.3.1) that converts that argument to the corresponding
5695 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005696 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005697 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005698 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005699 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005700 /*InOverloadResolution=*/true,
5701 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005702 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005703 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005704 if (Candidate.Conversions[ArgIdx].isBad()) {
5705 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005706 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005707 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005708 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005709 } else {
5710 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5711 // argument for which there is no corresponding parameter is
5712 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005713 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005714 }
5715 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005716
5717 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5718 Candidate.Viable = false;
5719 Candidate.FailureKind = ovl_fail_enable_if;
5720 Candidate.DeductionFailure.Data = FailedAttr;
5721 return;
5722 }
5723}
5724
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005725ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args,
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00005726 bool IsInstance) {
5727 SmallVector<ObjCMethodDecl*, 4> Methods;
5728 if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance))
5729 return nullptr;
5730
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005731 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5732 bool Match = true;
5733 ObjCMethodDecl *Method = Methods[b];
5734 unsigned NumNamedArgs = Sel.getNumArgs();
5735 // Method might have more arguments than selector indicates. This is due
5736 // to addition of c-style arguments in method.
5737 if (Method->param_size() > NumNamedArgs)
5738 NumNamedArgs = Method->param_size();
5739 if (Args.size() < NumNamedArgs)
5740 continue;
5741
5742 for (unsigned i = 0; i < NumNamedArgs; i++) {
5743 // We can't do any type-checking on a type-dependent argument.
5744 if (Args[i]->isTypeDependent()) {
5745 Match = false;
5746 break;
5747 }
5748
5749 ParmVarDecl *param = Method->parameters()[i];
5750 Expr *argExpr = Args[i];
5751 assert(argExpr && "SelectBestMethod(): missing expression");
5752
5753 // Strip the unbridged-cast placeholder expression off unless it's
5754 // a consumed argument.
5755 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5756 !param->hasAttr<CFConsumedAttr>())
5757 argExpr = stripARCUnbridgedCast(argExpr);
5758
5759 // If the parameter is __unknown_anytype, move on to the next method.
5760 if (param->getType() == Context.UnknownAnyTy) {
5761 Match = false;
5762 break;
5763 }
5764
5765 ImplicitConversionSequence ConversionState
5766 = TryCopyInitialization(*this, argExpr, param->getType(),
5767 /*SuppressUserConversions*/false,
5768 /*InOverloadResolution=*/true,
5769 /*AllowObjCWritebackConversion=*/
5770 getLangOpts().ObjCAutoRefCount,
5771 /*AllowExplicit*/false);
5772 if (ConversionState.isBad()) {
5773 Match = false;
5774 break;
5775 }
5776 }
5777 // Promote additional arguments to variadic methods.
5778 if (Match && Method->isVariadic()) {
5779 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
5780 if (Args[i]->isTypeDependent()) {
5781 Match = false;
5782 break;
5783 }
5784 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
5785 nullptr);
5786 if (Arg.isInvalid()) {
5787 Match = false;
5788 break;
5789 }
5790 }
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005791 } else {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005792 // Check for extra arguments to non-variadic methods.
5793 if (Args.size() != NumNamedArgs)
5794 Match = false;
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005795 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
5796 // Special case when selectors have no argument. In this case, select
5797 // one with the most general result type of 'id'.
5798 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5799 QualType ReturnT = Methods[b]->getReturnType();
5800 if (ReturnT->isObjCIdType())
5801 return Methods[b];
5802 }
5803 }
5804 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005805
5806 if (Match)
5807 return Method;
5808 }
5809 return nullptr;
5810}
5811
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005812static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); }
5813
5814EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5815 bool MissingImplicitThis) {
5816 // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but
5817 // we need to find the first failing one.
5818 if (!Function->hasAttrs())
Craig Topperc3ec1492014-05-26 06:22:03 +00005819 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005820 AttrVec Attrs = Function->getAttrs();
5821 AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(),
5822 IsNotEnableIfAttr);
5823 if (Attrs.begin() == E)
Craig Topperc3ec1492014-05-26 06:22:03 +00005824 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005825 std::reverse(Attrs.begin(), E);
5826
5827 SFINAETrap Trap(*this);
5828
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005829 SmallVector<Expr *, 16> ConvertedArgs;
5830 bool InitializationFailed = false;
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005831 bool ContainsValueDependentExpr = false;
Nick Lewyckye283c552015-08-25 22:33:16 +00005832
5833 // Convert the arguments.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005834 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5835 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
Nick Lewyckyb8336b72014-02-28 05:26:13 +00005836 !cast<CXXMethodDecl>(Function)->isStatic() &&
5837 !isa<CXXConstructorDecl>(Function)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005838 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5839 ExprResult R =
Craig Topperc3ec1492014-05-26 06:22:03 +00005840 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005841 Method, Method);
5842 if (R.isInvalid()) {
5843 InitializationFailed = true;
5844 break;
5845 }
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005846 ContainsValueDependentExpr |= R.get()->isValueDependent();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005847 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005848 } else {
5849 ExprResult R =
5850 PerformCopyInitialization(InitializedEntity::InitializeParameter(
5851 Context,
5852 Function->getParamDecl(i)),
5853 SourceLocation(),
5854 Args[i]);
5855 if (R.isInvalid()) {
5856 InitializationFailed = true;
5857 break;
5858 }
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005859 ContainsValueDependentExpr |= R.get()->isValueDependent();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005860 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005861 }
5862 }
5863
5864 if (InitializationFailed || Trap.hasErrorOccurred())
5865 return cast<EnableIfAttr>(Attrs[0]);
5866
Nick Lewyckye283c552015-08-25 22:33:16 +00005867 // Push default arguments if needed.
5868 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
5869 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
5870 ParmVarDecl *P = Function->getParamDecl(i);
5871 ExprResult R = PerformCopyInitialization(
5872 InitializedEntity::InitializeParameter(Context,
5873 Function->getParamDecl(i)),
5874 SourceLocation(),
5875 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
5876 : P->getDefaultArg());
5877 if (R.isInvalid()) {
5878 InitializationFailed = true;
5879 break;
5880 }
5881 ContainsValueDependentExpr |= R.get()->isValueDependent();
5882 ConvertedArgs.push_back(R.get());
5883 }
5884
5885 if (InitializationFailed || Trap.hasErrorOccurred())
5886 return cast<EnableIfAttr>(Attrs[0]);
5887 }
5888
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005889 for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) {
5890 APValue Result;
5891 EnableIfAttr *EIA = cast<EnableIfAttr>(*I);
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005892 if (EIA->getCond()->isValueDependent()) {
5893 // Don't even try now, we'll examine it after instantiation.
5894 continue;
5895 }
5896
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005897 if (!EIA->getCond()->EvaluateWithSubstitution(
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005898 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) {
5899 if (!ContainsValueDependentExpr)
5900 return EIA;
5901 } else if (!Result.isInt() || !Result.getInt().getBoolValue()) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005902 return EIA;
5903 }
5904 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005905 return nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005906}
5907
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005908/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00005909/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00005910void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005911 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005912 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005913 TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smithbcc22fc2012-03-09 08:00:36 +00005914 bool SuppressUserConversions,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005915 bool PartialOverloading) {
John McCall4c4c1df2010-01-26 03:27:55 +00005916 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00005917 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5918 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005919 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005920 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005921 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00005922 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005923 Args.slice(1), CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005924 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005925 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005926 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005927 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005928 } else {
John McCalla0296f72010-03-19 07:35:19 +00005929 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005930 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5931 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005932 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005933 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005934 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005935 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005936 Args[0]->Classify(Context), Args.slice(1),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005937 CandidateSet, SuppressUserConversions,
5938 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005939 else
John McCalla0296f72010-03-19 07:35:19 +00005940 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005941 ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005942 CandidateSet, SuppressUserConversions,
5943 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005944 }
Douglas Gregor15448f82009-06-27 21:05:07 +00005945 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005946}
5947
John McCallf0f1cf02009-11-17 07:50:12 +00005948/// AddMethodCandidate - Adds a named decl (which is some kind of
5949/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00005950void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005951 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005952 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005953 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00005954 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005955 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00005956 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00005957 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00005958
5959 if (isa<UsingShadowDecl>(Decl))
5960 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005961
John McCallf0f1cf02009-11-17 07:50:12 +00005962 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5963 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5964 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00005965 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
Craig Topperc3ec1492014-05-26 06:22:03 +00005966 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005967 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005968 Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005969 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005970 } else {
John McCalla0296f72010-03-19 07:35:19 +00005971 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005972 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005973 Args,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005974 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005975 }
5976}
5977
Douglas Gregor436424c2008-11-18 23:14:02 +00005978/// AddMethodCandidate - Adds the given C++ member function to the set
5979/// of candidate functions, using the given function call arguments
5980/// and the object argument (@c Object). For example, in a call
5981/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5982/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5983/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00005984/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00005985void
John McCalla0296f72010-03-19 07:35:19 +00005986Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00005987 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005988 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005989 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005990 OverloadCandidateSet &CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005991 bool SuppressUserConversions,
5992 bool PartialOverloading) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005993 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005994 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00005995 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005996 assert(!isa<CXXConstructorDecl>(Method) &&
5997 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00005998
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005999 if (!CandidateSet.isNewCandidate(Method))
6000 return;
6001
Richard Smith8b86f2d2013-11-04 01:48:18 +00006002 // C++11 [class.copy]p23: [DR1402]
6003 // A defaulted move assignment operator that is defined as deleted is
6004 // ignored by overload resolution.
6005 if (Method->isDefaulted() && Method->isDeleted() &&
6006 Method->isMoveAssignmentOperator())
6007 return;
6008
Douglas Gregor27381f32009-11-23 12:27:39 +00006009 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006010 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006011
Douglas Gregor436424c2008-11-18 23:14:02 +00006012 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006013 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006014 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00006015 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006016 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006017 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006018 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00006019
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006020 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00006021
6022 // (C++ 13.3.2p2): A candidate function having fewer than m
6023 // parameters is viable only if it has an ellipsis in its parameter
6024 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006025 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6026 !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006027 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006028 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006029 return;
6030 }
6031
6032 // (C++ 13.3.2p2): A candidate function having more than m parameters
6033 // is viable only if the (m+1)st parameter has a default argument
6034 // (8.3.6). For the purposes of overload resolution, the
6035 // parameter list is truncated on the right, so that there are
6036 // exactly m parameters.
6037 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006038 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006039 // Not enough arguments.
6040 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006041 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006042 return;
6043 }
6044
6045 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00006046
John McCall6e9f8f62009-12-03 04:06:58 +00006047 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006048 // The implicit object argument is ignored.
6049 Candidate.IgnoreObjectArgument = true;
6050 else {
6051 // Determine the implicit conversion sequence for the object
6052 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00006053 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00006054 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
6055 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006056 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006057 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006058 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006059 return;
6060 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006061 }
6062
Eli Bendersky291a57e2014-09-25 23:59:08 +00006063 // (CUDA B.1): Check for invalid calls between targets.
6064 if (getLangOpts().CUDA)
6065 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6066 if (CheckCUDATarget(Caller, Method)) {
6067 Candidate.Viable = false;
6068 Candidate.FailureKind = ovl_fail_bad_target;
6069 return;
6070 }
6071
Douglas Gregor436424c2008-11-18 23:14:02 +00006072 // Determine the implicit conversion sequences for each of the
6073 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006074 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006075 if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006076 // (C++ 13.3.2p3): for F to be a viable function, there shall
6077 // exist for each argument an implicit conversion sequence
6078 // (13.3.3.1) that converts that argument to the corresponding
6079 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006080 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006081 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006082 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006083 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006084 /*InOverloadResolution=*/true,
6085 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006086 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006087 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006088 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006089 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006090 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006091 }
6092 } else {
6093 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6094 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006095 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006096 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00006097 }
6098 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006099
6100 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6101 Candidate.Viable = false;
6102 Candidate.FailureKind = ovl_fail_enable_if;
6103 Candidate.DeductionFailure.Data = FailedAttr;
6104 return;
6105 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006106}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006107
Douglas Gregor97628d62009-08-21 00:16:32 +00006108/// \brief Add a C++ member function template as a candidate to the candidate
6109/// set, using template argument deduction to produce an appropriate member
6110/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006111void
Douglas Gregor97628d62009-08-21 00:16:32 +00006112Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00006113 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006114 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006115 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006116 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006117 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006118 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00006119 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006120 bool SuppressUserConversions,
6121 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006122 if (!CandidateSet.isNewCandidate(MethodTmpl))
6123 return;
6124
Douglas Gregor97628d62009-08-21 00:16:32 +00006125 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006126 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006127 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006128 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00006129 // candidate functions in the usual way.113) A given name can refer to one
6130 // or more function templates and also to a set of overloaded non-template
6131 // functions. In such a case, the candidate functions generated from each
6132 // function template are combined with the set of non-template candidate
6133 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006134 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006135 FunctionDecl *Specialization = nullptr;
Douglas Gregor97628d62009-08-21 00:16:32 +00006136 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006137 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006138 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006139 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006140 Candidate.FoundDecl = FoundDecl;
6141 Candidate.Function = MethodTmpl->getTemplatedDecl();
6142 Candidate.Viable = false;
6143 Candidate.FailureKind = ovl_fail_bad_deduction;
6144 Candidate.IsSurrogate = false;
6145 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006146 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006147 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006148 Info);
6149 return;
6150 }
Mike Stump11289f42009-09-09 15:08:12 +00006151
Douglas Gregor97628d62009-08-21 00:16:32 +00006152 // Add the function template specialization produced by template argument
6153 // deduction as a candidate.
6154 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00006155 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00006156 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00006157 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006158 ActingContext, ObjectType, ObjectClassification, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006159 CandidateSet, SuppressUserConversions, PartialOverloading);
Douglas Gregor97628d62009-08-21 00:16:32 +00006160}
6161
Douglas Gregor05155d82009-08-21 23:19:43 +00006162/// \brief Add a C++ function template specialization as a candidate
6163/// in the candidate set, using template argument deduction to produce
6164/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006165void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006166Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006167 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006168 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006169 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006170 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006171 bool SuppressUserConversions,
6172 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006173 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6174 return;
6175
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006176 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006177 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006178 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006179 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006180 // candidate functions in the usual way.113) A given name can refer to one
6181 // or more function templates and also to a set of overloaded non-template
6182 // functions. In such a case, the candidate functions generated from each
6183 // function template are combined with the set of non-template candidate
6184 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006185 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006186 FunctionDecl *Specialization = nullptr;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006187 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006188 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006189 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006190 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00006191 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00006192 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6193 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006194 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00006195 Candidate.IsSurrogate = false;
6196 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006197 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006198 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006199 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006200 return;
6201 }
Mike Stump11289f42009-09-09 15:08:12 +00006202
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006203 // Add the function template specialization produced by template argument
6204 // deduction as a candidate.
6205 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006206 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006207 SuppressUserConversions, PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006208}
Mike Stump11289f42009-09-09 15:08:12 +00006209
Douglas Gregor4b60a152013-11-07 22:34:54 +00006210/// Determine whether this is an allowable conversion from the result
6211/// of an explicit conversion operator to the expected type, per C++
6212/// [over.match.conv]p1 and [over.match.ref]p1.
6213///
6214/// \param ConvType The return type of the conversion function.
6215///
6216/// \param ToType The type we are converting to.
6217///
6218/// \param AllowObjCPointerConversion Allow a conversion from one
6219/// Objective-C pointer to another.
6220///
6221/// \returns true if the conversion is allowable, false otherwise.
6222static bool isAllowableExplicitConversion(Sema &S,
6223 QualType ConvType, QualType ToType,
6224 bool AllowObjCPointerConversion) {
6225 QualType ToNonRefType = ToType.getNonReferenceType();
6226
6227 // Easy case: the types are the same.
6228 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6229 return true;
6230
6231 // Allow qualification conversions.
6232 bool ObjCLifetimeConversion;
6233 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6234 ObjCLifetimeConversion))
6235 return true;
6236
6237 // If we're not allowed to consider Objective-C pointer conversions,
6238 // we're done.
6239 if (!AllowObjCPointerConversion)
6240 return false;
6241
6242 // Is this an Objective-C pointer conversion?
6243 bool IncompatibleObjC = false;
6244 QualType ConvertedType;
6245 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6246 IncompatibleObjC);
6247}
6248
Douglas Gregora1f013e2008-11-07 22:36:19 +00006249/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006250/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006251/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006252/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006253/// (which may or may not be the same type as the type that the
6254/// conversion function produces).
6255void
6256Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006257 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006258 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006259 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006260 OverloadCandidateSet& CandidateSet,
6261 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006262 assert(!Conversion->getDescribedFunctionTemplate() &&
6263 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006264 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006265 if (!CandidateSet.isNewCandidate(Conversion))
6266 return;
6267
Richard Smith2a7d4812013-05-04 07:00:32 +00006268 // If the conversion function has an undeduced return type, trigger its
6269 // deduction now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006270 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00006271 if (DeduceReturnType(Conversion, From->getExprLoc()))
6272 return;
6273 ConvType = Conversion->getConversionType().getNonReferenceType();
6274 }
6275
Richard Smith089c3162013-09-21 21:55:46 +00006276 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6277 // operator is only a candidate if its return type is the target type or
6278 // can be converted to the target type with a qualification conversion.
Douglas Gregor4b60a152013-11-07 22:34:54 +00006279 if (Conversion->isExplicit() &&
6280 !isAllowableExplicitConversion(*this, ConvType, ToType,
6281 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006282 return;
6283
Douglas Gregor27381f32009-11-23 12:27:39 +00006284 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006285 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006286
Douglas Gregora1f013e2008-11-07 22:36:19 +00006287 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006288 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006289 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006290 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006291 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006292 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006293 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006294 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006295 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006296 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006297 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006298
Douglas Gregor6affc782010-08-19 15:37:02 +00006299 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006300 // For conversion functions, the function is considered to be a member of
6301 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006302 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006303 //
6304 // Determine the implicit conversion sequence for the implicit
6305 // object parameter.
6306 QualType ImplicitParamType = From->getType();
6307 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6308 ImplicitParamType = FromPtrType->getPointeeType();
6309 CXXRecordDecl *ConversionContext
6310 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006311
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006312 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006313 = TryObjectArgumentInitialization(*this, From->getType(),
6314 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00006315 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006316
John McCall0d1da222010-01-12 00:44:57 +00006317 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006318 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006319 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006320 return;
6321 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006322
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006323 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006324 // derived to base as such conversions are given Conversion Rank. They only
6325 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6326 QualType FromCanon
6327 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6328 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6329 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
6330 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006331 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006332 return;
6333 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006334
Douglas Gregora1f013e2008-11-07 22:36:19 +00006335 // To determine what the conversion from the result of calling the
6336 // conversion function to the type we're eventually trying to
6337 // convert to (ToType), we need to synthesize a call to the
6338 // conversion function and attempt copy initialization from it. This
6339 // makes sure that we get the right semantics with respect to
6340 // lvalues/rvalues and the type. Fortunately, we can allocate this
6341 // call on the stack and we don't need its arguments to be
6342 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006343 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006344 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006345 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6346 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006347 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006348 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006349
Richard Smith48d24642011-07-13 22:53:21 +00006350 QualType ConversionType = Conversion->getConversionType();
6351 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006352 Candidate.Viable = false;
6353 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6354 return;
6355 }
6356
Richard Smith48d24642011-07-13 22:53:21 +00006357 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006358
Mike Stump11289f42009-09-09 15:08:12 +00006359 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006360 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6361 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006362 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006363 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006364 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006365 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006366 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006367 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006368 /*InOverloadResolution=*/false,
6369 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006370
John McCall0d1da222010-01-12 00:44:57 +00006371 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006372 case ImplicitConversionSequence::StandardConversion:
6373 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006374
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006375 // C++ [over.ics.user]p3:
6376 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006377 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006378 // shall have exact match rank.
6379 if (Conversion->getPrimaryTemplate() &&
6380 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6381 Candidate.Viable = false;
6382 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006383 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006384 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006385
Douglas Gregorcba72b12011-01-21 05:18:22 +00006386 // C++0x [dcl.init.ref]p5:
6387 // In the second case, if the reference is an rvalue reference and
6388 // the second standard conversion sequence of the user-defined
6389 // conversion sequence includes an lvalue-to-rvalue conversion, the
6390 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006391 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006392 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6393 Candidate.Viable = false;
6394 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006395 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006396 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006397 break;
6398
6399 case ImplicitConversionSequence::BadConversion:
6400 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006401 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006402 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006403
6404 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006405 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006406 "Can only end up with a standard conversion sequence or failure");
6407 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006408
Craig Topper5fc8fc22014-08-27 06:28:36 +00006409 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006410 Candidate.Viable = false;
6411 Candidate.FailureKind = ovl_fail_enable_if;
6412 Candidate.DeductionFailure.Data = FailedAttr;
6413 return;
6414 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006415}
6416
Douglas Gregor05155d82009-08-21 23:19:43 +00006417/// \brief Adds a conversion function template specialization
6418/// candidate to the overload set, using template argument deduction
6419/// to deduce the template arguments of the conversion function
6420/// template from the type that we are converting to (C++
6421/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006422void
Douglas Gregor05155d82009-08-21 23:19:43 +00006423Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006424 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006425 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00006426 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006427 OverloadCandidateSet &CandidateSet,
6428 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006429 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6430 "Only conversion function templates permitted here");
6431
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006432 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6433 return;
6434
Craig Toppere6706e42012-09-19 02:26:47 +00006435 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006436 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00006437 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006438 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006439 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006440 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006441 Candidate.FoundDecl = FoundDecl;
6442 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6443 Candidate.Viable = false;
6444 Candidate.FailureKind = ovl_fail_bad_deduction;
6445 Candidate.IsSurrogate = false;
6446 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006447 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006448 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006449 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006450 return;
6451 }
Mike Stump11289f42009-09-09 15:08:12 +00006452
Douglas Gregor05155d82009-08-21 23:19:43 +00006453 // Add the conversion function template specialization produced by
6454 // template argument deduction as a candidate.
6455 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00006456 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006457 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor05155d82009-08-21 23:19:43 +00006458}
6459
Douglas Gregorab7897a2008-11-19 22:57:39 +00006460/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6461/// converts the given @c Object to a function pointer via the
6462/// conversion function @c Conversion, and then attempts to call it
6463/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6464/// the type of function that we'll eventually be calling.
6465void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006466 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006467 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006468 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00006469 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006470 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00006471 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006472 if (!CandidateSet.isNewCandidate(Conversion))
6473 return;
6474
Douglas Gregor27381f32009-11-23 12:27:39 +00006475 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006476 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006477
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006478 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006479 Candidate.FoundDecl = FoundDecl;
Craig Topperc3ec1492014-05-26 06:22:03 +00006480 Candidate.Function = nullptr;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006481 Candidate.Surrogate = Conversion;
6482 Candidate.Viable = true;
6483 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006484 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006485 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006486
6487 // Determine the implicit conversion sequence for the implicit
6488 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00006489 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006490 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00006491 Object->Classify(Context),
6492 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006493 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006494 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006495 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00006496 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006497 return;
6498 }
6499
6500 // The first conversion is actually a user-defined conversion whose
6501 // first conversion is ObjectInit's standard conversion (which is
6502 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00006503 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006504 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00006505 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006506 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006507 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00006508 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00006509 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00006510 = Candidate.Conversions[0].UserDefined.Before;
6511 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6512
Mike Stump11289f42009-09-09 15:08:12 +00006513 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006514 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006515
6516 // (C++ 13.3.2p2): A candidate function having fewer than m
6517 // parameters is viable only if it has an ellipsis in its parameter
6518 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006519 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006520 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006521 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006522 return;
6523 }
6524
6525 // Function types don't have any default arguments, so just check if
6526 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006527 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006528 // Not enough arguments.
6529 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006530 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006531 return;
6532 }
6533
6534 // Determine the implicit conversion sequences for each of the
6535 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00006536 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006537 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006538 // (C++ 13.3.2p3): for F to be a viable function, there shall
6539 // exist for each argument an implicit conversion sequence
6540 // (13.3.3.1) that converts that argument to the corresponding
6541 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006542 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006543 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006544 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006545 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00006546 /*InOverloadResolution=*/false,
6547 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006548 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006549 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006550 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006551 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006552 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006553 }
6554 } else {
6555 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6556 // argument for which there is no corresponding parameter is
6557 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006558 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006559 }
6560 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006561
Craig Topper5fc8fc22014-08-27 06:28:36 +00006562 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006563 Candidate.Viable = false;
6564 Candidate.FailureKind = ovl_fail_enable_if;
6565 Candidate.DeductionFailure.Data = FailedAttr;
6566 return;
6567 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00006568}
6569
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006570/// \brief Add overload candidates for overloaded operators that are
6571/// member functions.
6572///
6573/// Add the overloaded operator candidates that are member functions
6574/// for the operator Op that was used in an operator expression such
6575/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6576/// CandidateSet will store the added overload candidates. (C++
6577/// [over.match.oper]).
6578void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6579 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00006580 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006581 OverloadCandidateSet& CandidateSet,
6582 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006583 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6584
6585 // C++ [over.match.oper]p3:
6586 // For a unary operator @ with an operand of a type whose
6587 // cv-unqualified version is T1, and for a binary operator @ with
6588 // a left operand of a type whose cv-unqualified version is T1 and
6589 // a right operand of a type whose cv-unqualified version is T2,
6590 // three sets of candidate functions, designated member
6591 // candidates, non-member candidates and built-in candidates, are
6592 // constructed as follows:
6593 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00006594
Richard Smith0feaf0c2013-04-20 12:41:22 +00006595 // -- If T1 is a complete class type or a class currently being
6596 // defined, the set of member candidates is the result of the
6597 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6598 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006599 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00006600 // Complete the type if it can be completed.
6601 RequireCompleteType(OpLoc, T1, 0);
6602 // If the type is neither complete nor being defined, bail out now.
6603 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006604 return;
Mike Stump11289f42009-09-09 15:08:12 +00006605
John McCall27b18f82009-11-17 02:14:36 +00006606 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6607 LookupQualifiedName(Operators, T1Rec->getDecl());
6608 Operators.suppressDiagnostics();
6609
Mike Stump11289f42009-09-09 15:08:12 +00006610 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006611 OperEnd = Operators.end();
6612 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00006613 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00006614 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola51629df2013-04-29 19:29:25 +00006615 Args[0]->Classify(Context),
Richard Smithe54c3072013-05-05 15:51:06 +00006616 Args.slice(1),
Douglas Gregor02824322011-01-26 19:30:28 +00006617 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006618 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00006619 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006620}
6621
Douglas Gregora11693b2008-11-12 17:17:38 +00006622/// AddBuiltinCandidate - Add a candidate for a built-in
6623/// operator. ResultTy and ParamTys are the result and parameter types
6624/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00006625/// arguments being passed to the candidate. IsAssignmentOperator
6626/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00006627/// operator. NumContextualBoolArguments is the number of arguments
6628/// (at the beginning of the argument list) that will be contextually
6629/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00006630void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smithe54c3072013-05-05 15:51:06 +00006631 ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00006632 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006633 bool IsAssignmentOperator,
6634 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00006635 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006636 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006637
Douglas Gregora11693b2008-11-12 17:17:38 +00006638 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00006639 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Craig Topperc3ec1492014-05-26 06:22:03 +00006640 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6641 Candidate.Function = nullptr;
Douglas Gregor1d248c52008-12-12 02:00:36 +00006642 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006643 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00006644 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smithe54c3072013-05-05 15:51:06 +00006645 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregora11693b2008-11-12 17:17:38 +00006646 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6647
6648 // Determine the implicit conversion sequences for each of the
6649 // arguments.
6650 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00006651 Candidate.ExplicitCallArguments = Args.size();
6652 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00006653 // C++ [over.match.oper]p4:
6654 // For the built-in assignment operators, conversions of the
6655 // left operand are restricted as follows:
6656 // -- no temporaries are introduced to hold the left operand, and
6657 // -- no user-defined conversions are applied to the left
6658 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00006659 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00006660 //
6661 // We block these conversions by turning off user-defined
6662 // conversions, since that is the only way that initialization of
6663 // a reference to a non-class type can occur from something that
6664 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006665 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006666 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006667 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006668 Candidate.Conversions[ArgIdx]
6669 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006670 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006671 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006672 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006673 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006674 /*InOverloadResolution=*/false,
6675 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006676 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006677 }
John McCall0d1da222010-01-12 00:44:57 +00006678 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006679 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006680 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006681 break;
6682 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006683 }
6684}
6685
Craig Toppercd7b0332013-07-01 06:29:40 +00006686namespace {
6687
Douglas Gregora11693b2008-11-12 17:17:38 +00006688/// BuiltinCandidateTypeSet - A set of types that will be used for the
6689/// candidate operator functions for built-in operators (C++
6690/// [over.built]). The types are separated into pointer types and
6691/// enumeration types.
6692class BuiltinCandidateTypeSet {
6693 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006694 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006695
6696 /// PointerTypes - The set of pointer types that will be used in the
6697 /// built-in candidates.
6698 TypeSet PointerTypes;
6699
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006700 /// MemberPointerTypes - The set of member pointer types that will be
6701 /// used in the built-in candidates.
6702 TypeSet MemberPointerTypes;
6703
Douglas Gregora11693b2008-11-12 17:17:38 +00006704 /// EnumerationTypes - The set of enumeration types that will be
6705 /// used in the built-in candidates.
6706 TypeSet EnumerationTypes;
6707
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006708 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006709 /// candidates.
6710 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006711
6712 /// \brief A flag indicating non-record types are viable candidates
6713 bool HasNonRecordTypes;
6714
6715 /// \brief A flag indicating whether either arithmetic or enumeration types
6716 /// were present in the candidate set.
6717 bool HasArithmeticOrEnumeralTypes;
6718
Douglas Gregor80af3132011-05-21 23:15:46 +00006719 /// \brief A flag indicating whether the nullptr type was present in the
6720 /// candidate set.
6721 bool HasNullPtrType;
6722
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006723 /// Sema - The semantic analysis instance where we are building the
6724 /// candidate type set.
6725 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006726
Douglas Gregora11693b2008-11-12 17:17:38 +00006727 /// Context - The AST context in which we will build the type sets.
6728 ASTContext &Context;
6729
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006730 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6731 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006732 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006733
6734public:
6735 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006736 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006737
Mike Stump11289f42009-09-09 15:08:12 +00006738 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006739 : HasNonRecordTypes(false),
6740 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006741 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006742 SemaRef(SemaRef),
6743 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006744
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006745 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006746 SourceLocation Loc,
6747 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006748 bool AllowExplicitConversions,
6749 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006750
6751 /// pointer_begin - First pointer type found;
6752 iterator pointer_begin() { return PointerTypes.begin(); }
6753
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006754 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006755 iterator pointer_end() { return PointerTypes.end(); }
6756
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006757 /// member_pointer_begin - First member pointer type found;
6758 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6759
6760 /// member_pointer_end - Past the last member pointer type found;
6761 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6762
Douglas Gregora11693b2008-11-12 17:17:38 +00006763 /// enumeration_begin - First enumeration type found;
6764 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6765
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006766 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006767 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006768
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006769 iterator vector_begin() { return VectorTypes.begin(); }
6770 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006771
6772 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6773 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006774 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006775};
6776
Craig Toppercd7b0332013-07-01 06:29:40 +00006777} // end anonymous namespace
6778
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006779/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006780/// the set of pointer types along with any more-qualified variants of
6781/// that type. For example, if @p Ty is "int const *", this routine
6782/// will add "int const *", "int const volatile *", "int const
6783/// restrict *", and "int const volatile restrict *" to the set of
6784/// pointer types. Returns true if the add of @p Ty itself succeeded,
6785/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006786///
6787/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006788bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006789BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6790 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006791
Douglas Gregora11693b2008-11-12 17:17:38 +00006792 // Insert this type.
David Blaikie82e95a32014-11-19 07:49:47 +00006793 if (!PointerTypes.insert(Ty).second)
Douglas Gregora11693b2008-11-12 17:17:38 +00006794 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006795
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006796 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006797 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006798 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006799 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006800 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6801 PointeeTy = PTy->getPointeeType();
6802 buildObjCPtr = true;
6803 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006804 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00006805 }
6806
Sebastian Redl4990a632009-11-18 20:39:26 +00006807 // Don't add qualified variants of arrays. For one, they're not allowed
6808 // (the qualifier would sink to the element type), and for another, the
6809 // only overload situation where it matters is subscript or pointer +- int,
6810 // and those shouldn't have qualifier variants anyway.
6811 if (PointeeTy->isArrayType())
6812 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006813
John McCall8ccfcb52009-09-24 19:53:00 +00006814 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006815 bool hasVolatile = VisibleQuals.hasVolatile();
6816 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006817
John McCall8ccfcb52009-09-24 19:53:00 +00006818 // Iterate through all strict supersets of BaseCVR.
6819 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6820 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006821 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006822 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006823
6824 // Skip over restrict if no restrict found anywhere in the types, or if
6825 // the type cannot be restrict-qualified.
6826 if ((CVR & Qualifiers::Restrict) &&
6827 (!hasRestrict ||
6828 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6829 continue;
6830
6831 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00006832 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006833
6834 // Build qualified pointer type.
6835 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006836 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00006837 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006838 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00006839 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6840
6841 // Insert qualified pointer type.
6842 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00006843 }
6844
6845 return true;
6846}
6847
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006848/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6849/// to the set of pointer types along with any more-qualified variants of
6850/// that type. For example, if @p Ty is "int const *", this routine
6851/// will add "int const *", "int const volatile *", "int const
6852/// restrict *", and "int const volatile restrict *" to the set of
6853/// pointer types. Returns true if the add of @p Ty itself succeeded,
6854/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006855///
6856/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006857bool
6858BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6859 QualType Ty) {
6860 // Insert this type.
David Blaikie82e95a32014-11-19 07:49:47 +00006861 if (!MemberPointerTypes.insert(Ty).second)
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006862 return false;
6863
John McCall8ccfcb52009-09-24 19:53:00 +00006864 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6865 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006866
John McCall8ccfcb52009-09-24 19:53:00 +00006867 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006868 // Don't add qualified variants of arrays. For one, they're not allowed
6869 // (the qualifier would sink to the element type), and for another, the
6870 // only overload situation where it matters is subscript or pointer +- int,
6871 // and those shouldn't have qualifier variants anyway.
6872 if (PointeeTy->isArrayType())
6873 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006874 const Type *ClassTy = PointerTy->getClass();
6875
6876 // Iterate through all strict supersets of the pointee type's CVR
6877 // qualifiers.
6878 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6879 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6880 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006881
John McCall8ccfcb52009-09-24 19:53:00 +00006882 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006883 MemberPointerTypes.insert(
6884 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006885 }
6886
6887 return true;
6888}
6889
Douglas Gregora11693b2008-11-12 17:17:38 +00006890/// AddTypesConvertedFrom - Add each of the types to which the type @p
6891/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006892/// primarily interested in pointer types and enumeration types. We also
6893/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006894/// AllowUserConversions is true if we should look at the conversion
6895/// functions of a class type, and AllowExplicitConversions if we
6896/// should also include the explicit conversion functions of a class
6897/// type.
Mike Stump11289f42009-09-09 15:08:12 +00006898void
Douglas Gregor5fb53972009-01-14 15:45:31 +00006899BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006900 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006901 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006902 bool AllowExplicitConversions,
6903 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006904 // Only deal with canonical types.
6905 Ty = Context.getCanonicalType(Ty);
6906
6907 // Look through reference types; they aren't part of the type of an
6908 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006909 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00006910 Ty = RefTy->getPointeeType();
6911
John McCall33ddac02011-01-19 10:06:00 +00006912 // If we're dealing with an array type, decay to the pointer.
6913 if (Ty->isArrayType())
6914 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6915
6916 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006917 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00006918
Chandler Carruth00a38332010-12-13 01:44:01 +00006919 // Flag if we ever add a non-record type.
6920 const RecordType *TyRec = Ty->getAs<RecordType>();
6921 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6922
Chandler Carruth00a38332010-12-13 01:44:01 +00006923 // Flag if we encounter an arithmetic type.
6924 HasArithmeticOrEnumeralTypes =
6925 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6926
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006927 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6928 PointerTypes.insert(Ty);
6929 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006930 // Insert our type, and its more-qualified variants, into the set
6931 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006932 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00006933 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006934 } else if (Ty->isMemberPointerType()) {
6935 // Member pointers are far easier, since the pointee can't be converted.
6936 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6937 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00006938 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006939 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00006940 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006941 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006942 // We treat vector types as arithmetic types in many contexts as an
6943 // extension.
6944 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006945 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00006946 } else if (Ty->isNullPtrType()) {
6947 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00006948 } else if (AllowUserConversions && TyRec) {
6949 // No conversion functions in incomplete types.
6950 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6951 return;
Mike Stump11289f42009-09-09 15:08:12 +00006952
Chandler Carruth00a38332010-12-13 01:44:01 +00006953 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00006954 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006955 if (isa<UsingShadowDecl>(D))
6956 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00006957
Chandler Carruth00a38332010-12-13 01:44:01 +00006958 // Skip conversion function templates; they don't tell us anything
6959 // about which builtin types we can convert to.
6960 if (isa<FunctionTemplateDecl>(D))
6961 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006962
Chandler Carruth00a38332010-12-13 01:44:01 +00006963 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6964 if (AllowExplicitConversions || !Conv->isExplicit()) {
6965 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6966 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006967 }
6968 }
6969 }
6970}
6971
Douglas Gregor84605ae2009-08-24 13:43:27 +00006972/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6973/// the volatile- and non-volatile-qualified assignment operators for the
6974/// given type to the candidate set.
6975static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6976 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00006977 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006978 OverloadCandidateSet &CandidateSet) {
6979 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00006980
Douglas Gregor84605ae2009-08-24 13:43:27 +00006981 // T& operator=(T&, T)
6982 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6983 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00006984 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006985 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00006986
Douglas Gregor84605ae2009-08-24 13:43:27 +00006987 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6988 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00006989 ParamTypes[0]
6990 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00006991 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00006992 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00006993 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00006994 }
6995}
Mike Stump11289f42009-09-09 15:08:12 +00006996
Sebastian Redl1054fae2009-10-25 17:03:50 +00006997/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6998/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006999static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7000 Qualifiers VRQuals;
7001 const RecordType *TyRec;
7002 if (const MemberPointerType *RHSMPType =
7003 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00007004 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007005 else
7006 TyRec = ArgExpr->getType()->getAs<RecordType>();
7007 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007008 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007009 VRQuals.addVolatile();
7010 VRQuals.addRestrict();
7011 return VRQuals;
7012 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007013
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007014 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00007015 if (!ClassDecl->hasDefinition())
7016 return VRQuals;
7017
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007018 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
John McCallda4458e2010-03-31 01:36:47 +00007019 if (isa<UsingShadowDecl>(D))
7020 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7021 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007022 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7023 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7024 CanTy = ResTypeRef->getPointeeType();
7025 // Need to go down the pointer/mempointer chain and add qualifiers
7026 // as see them.
7027 bool done = false;
7028 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007029 if (CanTy.isRestrictQualified())
7030 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007031 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7032 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007033 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007034 CanTy->getAs<MemberPointerType>())
7035 CanTy = ResTypeMPtr->getPointeeType();
7036 else
7037 done = true;
7038 if (CanTy.isVolatileQualified())
7039 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007040 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7041 return VRQuals;
7042 }
7043 }
7044 }
7045 return VRQuals;
7046}
John McCall52872982010-11-13 05:51:15 +00007047
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007048namespace {
John McCall52872982010-11-13 05:51:15 +00007049
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007050/// \brief Helper class to manage the addition of builtin operator overload
7051/// candidates. It provides shared state and utility methods used throughout
7052/// the process, as well as a helper method to add each group of builtin
7053/// operator overloads from the standard to a candidate set.
7054class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007055 // Common instance state available to all overload candidate addition methods.
7056 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00007057 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007058 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00007059 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007060 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007061 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007062
Chandler Carruthc6586e52010-12-12 10:35:00 +00007063 // Define some constants used to index and iterate over the arithemetic types
7064 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00007065 // The "promoted arithmetic types" are the arithmetic
7066 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00007067 static const unsigned FirstIntegralType = 3;
Richard Smith521ecc12012-06-10 08:00:26 +00007068 static const unsigned LastIntegralType = 20;
John McCall52872982010-11-13 05:51:15 +00007069 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith521ecc12012-06-10 08:00:26 +00007070 LastPromotedIntegralType = 11;
John McCall52872982010-11-13 05:51:15 +00007071 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith521ecc12012-06-10 08:00:26 +00007072 LastPromotedArithmeticType = 11;
7073 static const unsigned NumArithmeticTypes = 20;
John McCall52872982010-11-13 05:51:15 +00007074
Chandler Carruthc6586e52010-12-12 10:35:00 +00007075 /// \brief Get the canonical type for a given arithmetic type index.
7076 CanQualType getArithmeticType(unsigned index) {
7077 assert(index < NumArithmeticTypes);
7078 static CanQualType ASTContext::* const
7079 ArithmeticTypes[NumArithmeticTypes] = {
7080 // Start of promoted types.
7081 &ASTContext::FloatTy,
7082 &ASTContext::DoubleTy,
7083 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00007084
Chandler Carruthc6586e52010-12-12 10:35:00 +00007085 // Start of integral types.
7086 &ASTContext::IntTy,
7087 &ASTContext::LongTy,
7088 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007089 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007090 &ASTContext::UnsignedIntTy,
7091 &ASTContext::UnsignedLongTy,
7092 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007093 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007094 // End of promoted types.
7095
7096 &ASTContext::BoolTy,
7097 &ASTContext::CharTy,
7098 &ASTContext::WCharTy,
7099 &ASTContext::Char16Ty,
7100 &ASTContext::Char32Ty,
7101 &ASTContext::SignedCharTy,
7102 &ASTContext::ShortTy,
7103 &ASTContext::UnsignedCharTy,
7104 &ASTContext::UnsignedShortTy,
7105 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00007106 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00007107 };
7108 return S.Context.*ArithmeticTypes[index];
7109 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007110
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007111 /// \brief Gets the canonical type resulting from the usual arithemetic
7112 /// converions for the given arithmetic types.
7113 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7114 // Accelerator table for performing the usual arithmetic conversions.
7115 // The rules are basically:
7116 // - if either is floating-point, use the wider floating-point
7117 // - if same signedness, use the higher rank
7118 // - if same size, use unsigned of the higher rank
7119 // - use the larger type
7120 // These rules, together with the axiom that higher ranks are
7121 // never smaller, are sufficient to precompute all of these results
7122 // *except* when dealing with signed types of higher rank.
7123 // (we could precompute SLL x UI for all known platforms, but it's
7124 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00007125 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007126 enum PromotedType {
Richard Smith521ecc12012-06-10 08:00:26 +00007127 Dep=-1,
7128 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007129 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00007130 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007131 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00007132/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7133/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7134/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7135/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7136/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7137/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7138/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7139/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7140/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7141/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7142/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007143 };
7144
7145 assert(L < LastPromotedArithmeticType);
7146 assert(R < LastPromotedArithmeticType);
7147 int Idx = ConversionsTable[L][R];
7148
7149 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007150 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007151
7152 // Slow path: we need to compare widths.
7153 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007154 CanQualType LT = getArithmeticType(L),
7155 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007156 unsigned LW = S.Context.getIntWidth(LT),
7157 RW = S.Context.getIntWidth(RT);
7158
7159 // If they're different widths, use the signed type.
7160 if (LW > RW) return LT;
7161 else if (LW < RW) return RT;
7162
7163 // Otherwise, use the unsigned type of the signed type's rank.
7164 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7165 assert(L == SLL || R == SLL);
7166 return S.Context.UnsignedLongLongTy;
7167 }
7168
Chandler Carruth5659c0c2010-12-12 09:22:45 +00007169 /// \brief Helper method to factor out the common pattern of adding overloads
7170 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007171 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007172 bool HasVolatile,
7173 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007174 QualType ParamTypes[2] = {
7175 S.Context.getLValueReferenceType(CandidateTy),
7176 S.Context.IntTy
7177 };
7178
7179 // Non-volatile version.
Richard Smithe54c3072013-05-05 15:51:06 +00007180 if (Args.size() == 1)
7181 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007182 else
Richard Smithe54c3072013-05-05 15:51:06 +00007183 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007184
7185 // Use a heuristic to reduce number of builtin candidates in the set:
7186 // add volatile version only if there are conversions to a volatile type.
7187 if (HasVolatile) {
7188 ParamTypes[0] =
7189 S.Context.getLValueReferenceType(
7190 S.Context.getVolatileType(CandidateTy));
Richard Smithe54c3072013-05-05 15:51:06 +00007191 if (Args.size() == 1)
7192 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007193 else
Richard Smithe54c3072013-05-05 15:51:06 +00007194 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007195 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007196
7197 // Add restrict version only if there are conversions to a restrict type
7198 // and our candidate type is a non-restrict-qualified pointer.
7199 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7200 !CandidateTy.isRestrictQualified()) {
7201 ParamTypes[0]
7202 = S.Context.getLValueReferenceType(
7203 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smithe54c3072013-05-05 15:51:06 +00007204 if (Args.size() == 1)
7205 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007206 else
Richard Smithe54c3072013-05-05 15:51:06 +00007207 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007208
7209 if (HasVolatile) {
7210 ParamTypes[0]
7211 = S.Context.getLValueReferenceType(
7212 S.Context.getCVRQualifiedType(CandidateTy,
7213 (Qualifiers::Volatile |
7214 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007215 if (Args.size() == 1)
7216 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007217 else
Richard Smithe54c3072013-05-05 15:51:06 +00007218 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007219 }
7220 }
7221
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007222 }
7223
7224public:
7225 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007226 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007227 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007228 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007229 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007230 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007231 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007232 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007233 HasArithmeticOrEnumeralCandidateType(
7234 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007235 CandidateTypes(CandidateTypes),
7236 CandidateSet(CandidateSet) {
7237 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007238 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007239 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007240 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007241 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007242 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007243 assert(getArithmeticType(FirstPromotedArithmeticType)
7244 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007245 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007246 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007247 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007248 "Invalid last promoted arithmetic type");
7249 }
7250
7251 // C++ [over.built]p3:
7252 //
7253 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7254 // is either volatile or empty, there exist candidate operator
7255 // functions of the form
7256 //
7257 // VQ T& operator++(VQ T&);
7258 // T operator++(VQ T&, int);
7259 //
7260 // C++ [over.built]p4:
7261 //
7262 // For every pair (T, VQ), where T is an arithmetic type other
7263 // than bool, and VQ is either volatile or empty, there exist
7264 // candidate operator functions of the form
7265 //
7266 // VQ T& operator--(VQ T&);
7267 // T operator--(VQ T&, int);
7268 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007269 if (!HasArithmeticOrEnumeralCandidateType)
7270 return;
7271
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007272 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7273 Arith < NumArithmeticTypes; ++Arith) {
7274 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007275 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007276 VisibleTypeConversionsQuals.hasVolatile(),
7277 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007278 }
7279 }
7280
7281 // C++ [over.built]p5:
7282 //
7283 // For every pair (T, VQ), where T is a cv-qualified or
7284 // cv-unqualified object type, and VQ is either volatile or
7285 // empty, there exist candidate operator functions of the form
7286 //
7287 // T*VQ& operator++(T*VQ&);
7288 // T*VQ& operator--(T*VQ&);
7289 // T* operator++(T*VQ&, int);
7290 // T* operator--(T*VQ&, int);
7291 void addPlusPlusMinusMinusPointerOverloads() {
7292 for (BuiltinCandidateTypeSet::iterator
7293 Ptr = CandidateTypes[0].pointer_begin(),
7294 PtrEnd = CandidateTypes[0].pointer_end();
7295 Ptr != PtrEnd; ++Ptr) {
7296 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007297 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007298 continue;
7299
7300 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007301 (!(*Ptr).isVolatileQualified() &&
7302 VisibleTypeConversionsQuals.hasVolatile()),
7303 (!(*Ptr).isRestrictQualified() &&
7304 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007305 }
7306 }
7307
7308 // C++ [over.built]p6:
7309 // For every cv-qualified or cv-unqualified object type T, there
7310 // exist candidate operator functions of the form
7311 //
7312 // T& operator*(T*);
7313 //
7314 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007315 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007316 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007317 // T& operator*(T*);
7318 void addUnaryStarPointerOverloads() {
7319 for (BuiltinCandidateTypeSet::iterator
7320 Ptr = CandidateTypes[0].pointer_begin(),
7321 PtrEnd = CandidateTypes[0].pointer_end();
7322 Ptr != PtrEnd; ++Ptr) {
7323 QualType ParamTy = *Ptr;
7324 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007325 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7326 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007327
Douglas Gregor02824322011-01-26 19:30:28 +00007328 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7329 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7330 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007331
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007332 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smithe54c3072013-05-05 15:51:06 +00007333 &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007334 }
7335 }
7336
7337 // C++ [over.built]p9:
7338 // For every promoted arithmetic type T, there exist candidate
7339 // operator functions of the form
7340 //
7341 // T operator+(T);
7342 // T operator-(T);
7343 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007344 if (!HasArithmeticOrEnumeralCandidateType)
7345 return;
7346
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007347 for (unsigned Arith = FirstPromotedArithmeticType;
7348 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007349 QualType ArithTy = getArithmeticType(Arith);
Richard Smithe54c3072013-05-05 15:51:06 +00007350 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007351 }
7352
7353 // Extension: We also add these operators for vector types.
7354 for (BuiltinCandidateTypeSet::iterator
7355 Vec = CandidateTypes[0].vector_begin(),
7356 VecEnd = CandidateTypes[0].vector_end();
7357 Vec != VecEnd; ++Vec) {
7358 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007359 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007360 }
7361 }
7362
7363 // C++ [over.built]p8:
7364 // For every type T, there exist candidate operator functions of
7365 // the form
7366 //
7367 // T* operator+(T*);
7368 void addUnaryPlusPointerOverloads() {
7369 for (BuiltinCandidateTypeSet::iterator
7370 Ptr = CandidateTypes[0].pointer_begin(),
7371 PtrEnd = CandidateTypes[0].pointer_end();
7372 Ptr != PtrEnd; ++Ptr) {
7373 QualType ParamTy = *Ptr;
Richard Smithe54c3072013-05-05 15:51:06 +00007374 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007375 }
7376 }
7377
7378 // C++ [over.built]p10:
7379 // For every promoted integral type T, there exist candidate
7380 // operator functions of the form
7381 //
7382 // T operator~(T);
7383 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007384 if (!HasArithmeticOrEnumeralCandidateType)
7385 return;
7386
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007387 for (unsigned Int = FirstPromotedIntegralType;
7388 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007389 QualType IntTy = getArithmeticType(Int);
Richard Smithe54c3072013-05-05 15:51:06 +00007390 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007391 }
7392
7393 // Extension: We also add this operator for vector types.
7394 for (BuiltinCandidateTypeSet::iterator
7395 Vec = CandidateTypes[0].vector_begin(),
7396 VecEnd = CandidateTypes[0].vector_end();
7397 Vec != VecEnd; ++Vec) {
7398 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007399 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007400 }
7401 }
7402
7403 // C++ [over.match.oper]p16:
7404 // For every pointer to member type T, there exist candidate operator
7405 // functions of the form
7406 //
7407 // bool operator==(T,T);
7408 // bool operator!=(T,T);
7409 void addEqualEqualOrNotEqualMemberPointerOverloads() {
7410 /// Set of (canonical) types that we've already handled.
7411 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7412
Richard Smithe54c3072013-05-05 15:51:06 +00007413 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007414 for (BuiltinCandidateTypeSet::iterator
7415 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7416 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7417 MemPtr != MemPtrEnd;
7418 ++MemPtr) {
7419 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007420 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007421 continue;
7422
7423 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007424 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007425 }
7426 }
7427 }
7428
7429 // C++ [over.built]p15:
7430 //
Douglas Gregor80af3132011-05-21 23:15:46 +00007431 // For every T, where T is an enumeration type, a pointer type, or
7432 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007433 //
7434 // bool operator<(T, T);
7435 // bool operator>(T, T);
7436 // bool operator<=(T, T);
7437 // bool operator>=(T, T);
7438 // bool operator==(T, T);
7439 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007440 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007441 // C++ [over.match.oper]p3:
7442 // [...]the built-in candidates include all of the candidate operator
7443 // functions defined in 13.6 that, compared to the given operator, [...]
7444 // do not have the same parameter-type-list as any non-template non-member
7445 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007446 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007447 // Note that in practice, this only affects enumeration types because there
7448 // aren't any built-in candidates of record type, and a user-defined operator
7449 // must have an operand of record or enumeration type. Also, the only other
7450 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007451 // cannot be overloaded for enumeration types, so this is the only place
7452 // where we must suppress candidates like this.
7453 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7454 UserDefinedBinaryOperators;
7455
Richard Smithe54c3072013-05-05 15:51:06 +00007456 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007457 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7458 CandidateTypes[ArgIdx].enumeration_end()) {
7459 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7460 CEnd = CandidateSet.end();
7461 C != CEnd; ++C) {
7462 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7463 continue;
7464
Eli Friedman14f082b2012-09-18 21:52:24 +00007465 if (C->Function->isFunctionTemplateSpecialization())
7466 continue;
7467
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007468 QualType FirstParamType =
7469 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7470 QualType SecondParamType =
7471 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7472
7473 // Skip if either parameter isn't of enumeral type.
7474 if (!FirstParamType->isEnumeralType() ||
7475 !SecondParamType->isEnumeralType())
7476 continue;
7477
7478 // Add this operator to the set of known user-defined operators.
7479 UserDefinedBinaryOperators.insert(
7480 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7481 S.Context.getCanonicalType(SecondParamType)));
7482 }
7483 }
7484 }
7485
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007486 /// Set of (canonical) types that we've already handled.
7487 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7488
Richard Smithe54c3072013-05-05 15:51:06 +00007489 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007490 for (BuiltinCandidateTypeSet::iterator
7491 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7492 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7493 Ptr != PtrEnd; ++Ptr) {
7494 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007495 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007496 continue;
7497
7498 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007499 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007500 }
7501 for (BuiltinCandidateTypeSet::iterator
7502 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7503 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7504 Enum != EnumEnd; ++Enum) {
7505 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7506
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007507 // Don't add the same builtin candidate twice, or if a user defined
7508 // candidate exists.
David Blaikie82e95a32014-11-19 07:49:47 +00007509 if (!AddedTypes.insert(CanonType).second ||
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007510 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7511 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007512 continue;
7513
7514 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007515 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007516 }
Douglas Gregor80af3132011-05-21 23:15:46 +00007517
7518 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7519 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
David Blaikie82e95a32014-11-19 07:49:47 +00007520 if (AddedTypes.insert(NullPtrTy).second &&
Richard Smithe54c3072013-05-05 15:51:06 +00007521 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor80af3132011-05-21 23:15:46 +00007522 NullPtrTy))) {
7523 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007524 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor80af3132011-05-21 23:15:46 +00007525 CandidateSet);
7526 }
7527 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007528 }
7529 }
7530
7531 // C++ [over.built]p13:
7532 //
7533 // For every cv-qualified or cv-unqualified object type T
7534 // there exist candidate operator functions of the form
7535 //
7536 // T* operator+(T*, ptrdiff_t);
7537 // T& operator[](T*, ptrdiff_t); [BELOW]
7538 // T* operator-(T*, ptrdiff_t);
7539 // T* operator+(ptrdiff_t, T*);
7540 // T& operator[](ptrdiff_t, T*); [BELOW]
7541 //
7542 // C++ [over.built]p14:
7543 //
7544 // For every T, where T is a pointer to object type, there
7545 // exist candidate operator functions of the form
7546 //
7547 // ptrdiff_t operator-(T, T);
7548 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7549 /// Set of (canonical) types that we've already handled.
7550 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7551
7552 for (int Arg = 0; Arg < 2; ++Arg) {
Eric Christopher9207a522015-08-21 16:24:01 +00007553 QualType AsymmetricParamTypes[2] = {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007554 S.Context.getPointerDiffType(),
7555 S.Context.getPointerDiffType(),
7556 };
7557 for (BuiltinCandidateTypeSet::iterator
7558 Ptr = CandidateTypes[Arg].pointer_begin(),
7559 PtrEnd = CandidateTypes[Arg].pointer_end();
7560 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00007561 QualType PointeeTy = (*Ptr)->getPointeeType();
7562 if (!PointeeTy->isObjectType())
7563 continue;
7564
Eric Christopher9207a522015-08-21 16:24:01 +00007565 AsymmetricParamTypes[Arg] = *Ptr;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007566 if (Arg == 0 || Op == OO_Plus) {
7567 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7568 // T* operator+(ptrdiff_t, T*);
Eric Christopher9207a522015-08-21 16:24:01 +00007569 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007570 }
7571 if (Op == OO_Minus) {
7572 // ptrdiff_t operator-(T, T);
David Blaikie82e95a32014-11-19 07:49:47 +00007573 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007574 continue;
7575
7576 QualType ParamTypes[2] = { *Ptr, *Ptr };
7577 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smithe54c3072013-05-05 15:51:06 +00007578 Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007579 }
7580 }
7581 }
7582 }
7583
7584 // C++ [over.built]p12:
7585 //
7586 // For every pair of promoted arithmetic types L and R, there
7587 // exist candidate operator functions of the form
7588 //
7589 // LR operator*(L, R);
7590 // LR operator/(L, R);
7591 // LR operator+(L, R);
7592 // LR operator-(L, R);
7593 // bool operator<(L, R);
7594 // bool operator>(L, R);
7595 // bool operator<=(L, R);
7596 // bool operator>=(L, R);
7597 // bool operator==(L, R);
7598 // bool operator!=(L, R);
7599 //
7600 // where LR is the result of the usual arithmetic conversions
7601 // between types L and R.
7602 //
7603 // C++ [over.built]p24:
7604 //
7605 // For every pair of promoted arithmetic types L and R, there exist
7606 // candidate operator functions of the form
7607 //
7608 // LR operator?(bool, L, R);
7609 //
7610 // where LR is the result of the usual arithmetic conversions
7611 // between types L and R.
7612 // Our candidates ignore the first parameter.
7613 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007614 if (!HasArithmeticOrEnumeralCandidateType)
7615 return;
7616
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007617 for (unsigned Left = FirstPromotedArithmeticType;
7618 Left < LastPromotedArithmeticType; ++Left) {
7619 for (unsigned Right = FirstPromotedArithmeticType;
7620 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007621 QualType LandR[2] = { getArithmeticType(Left),
7622 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007623 QualType Result =
7624 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007625 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007626 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007627 }
7628 }
7629
7630 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7631 // conditional operator for vector types.
7632 for (BuiltinCandidateTypeSet::iterator
7633 Vec1 = CandidateTypes[0].vector_begin(),
7634 Vec1End = CandidateTypes[0].vector_end();
7635 Vec1 != Vec1End; ++Vec1) {
7636 for (BuiltinCandidateTypeSet::iterator
7637 Vec2 = CandidateTypes[1].vector_begin(),
7638 Vec2End = CandidateTypes[1].vector_end();
7639 Vec2 != Vec2End; ++Vec2) {
7640 QualType LandR[2] = { *Vec1, *Vec2 };
7641 QualType Result = S.Context.BoolTy;
7642 if (!isComparison) {
7643 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7644 Result = *Vec1;
7645 else
7646 Result = *Vec2;
7647 }
7648
Richard Smithe54c3072013-05-05 15:51:06 +00007649 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007650 }
7651 }
7652 }
7653
7654 // C++ [over.built]p17:
7655 //
7656 // For every pair of promoted integral types L and R, there
7657 // exist candidate operator functions of the form
7658 //
7659 // LR operator%(L, R);
7660 // LR operator&(L, R);
7661 // LR operator^(L, R);
7662 // LR operator|(L, R);
7663 // L operator<<(L, R);
7664 // L operator>>(L, R);
7665 //
7666 // where LR is the result of the usual arithmetic conversions
7667 // between types L and R.
7668 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007669 if (!HasArithmeticOrEnumeralCandidateType)
7670 return;
7671
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007672 for (unsigned Left = FirstPromotedIntegralType;
7673 Left < LastPromotedIntegralType; ++Left) {
7674 for (unsigned Right = FirstPromotedIntegralType;
7675 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007676 QualType LandR[2] = { getArithmeticType(Left),
7677 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007678 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7679 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007680 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007681 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007682 }
7683 }
7684 }
7685
7686 // C++ [over.built]p20:
7687 //
7688 // For every pair (T, VQ), where T is an enumeration or
7689 // pointer to member type and VQ is either volatile or
7690 // empty, there exist candidate operator functions of the form
7691 //
7692 // VQ T& operator=(VQ T&, T);
7693 void addAssignmentMemberPointerOrEnumeralOverloads() {
7694 /// Set of (canonical) types that we've already handled.
7695 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7696
7697 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7698 for (BuiltinCandidateTypeSet::iterator
7699 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7700 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7701 Enum != EnumEnd; ++Enum) {
David Blaikie82e95a32014-11-19 07:49:47 +00007702 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007703 continue;
7704
Richard Smithe54c3072013-05-05 15:51:06 +00007705 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007706 }
7707
7708 for (BuiltinCandidateTypeSet::iterator
7709 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7710 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7711 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00007712 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007713 continue;
7714
Richard Smithe54c3072013-05-05 15:51:06 +00007715 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007716 }
7717 }
7718 }
7719
7720 // C++ [over.built]p19:
7721 //
7722 // For every pair (T, VQ), where T is any type and VQ is either
7723 // volatile or empty, there exist candidate operator functions
7724 // of the form
7725 //
7726 // T*VQ& operator=(T*VQ&, T*);
7727 //
7728 // C++ [over.built]p21:
7729 //
7730 // For every pair (T, VQ), where T is a cv-qualified or
7731 // cv-unqualified object type and VQ is either volatile or
7732 // empty, there exist candidate operator functions of the form
7733 //
7734 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7735 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7736 void addAssignmentPointerOverloads(bool isEqualOp) {
7737 /// Set of (canonical) types that we've already handled.
7738 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7739
7740 for (BuiltinCandidateTypeSet::iterator
7741 Ptr = CandidateTypes[0].pointer_begin(),
7742 PtrEnd = CandidateTypes[0].pointer_end();
7743 Ptr != PtrEnd; ++Ptr) {
7744 // If this is operator=, keep track of the builtin candidates we added.
7745 if (isEqualOp)
7746 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007747 else if (!(*Ptr)->getPointeeType()->isObjectType())
7748 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007749
7750 // non-volatile version
7751 QualType ParamTypes[2] = {
7752 S.Context.getLValueReferenceType(*Ptr),
7753 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7754 };
Richard Smithe54c3072013-05-05 15:51:06 +00007755 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007756 /*IsAssigmentOperator=*/ isEqualOp);
7757
Douglas Gregor5bee2582012-06-04 00:15:09 +00007758 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7759 VisibleTypeConversionsQuals.hasVolatile();
7760 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007761 // volatile version
7762 ParamTypes[0] =
7763 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007764 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007765 /*IsAssigmentOperator=*/isEqualOp);
7766 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007767
7768 if (!(*Ptr).isRestrictQualified() &&
7769 VisibleTypeConversionsQuals.hasRestrict()) {
7770 // restrict version
7771 ParamTypes[0]
7772 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007773 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007774 /*IsAssigmentOperator=*/isEqualOp);
7775
7776 if (NeedVolatile) {
7777 // volatile restrict version
7778 ParamTypes[0]
7779 = S.Context.getLValueReferenceType(
7780 S.Context.getCVRQualifiedType(*Ptr,
7781 (Qualifiers::Volatile |
7782 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007783 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007784 /*IsAssigmentOperator=*/isEqualOp);
7785 }
7786 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007787 }
7788
7789 if (isEqualOp) {
7790 for (BuiltinCandidateTypeSet::iterator
7791 Ptr = CandidateTypes[1].pointer_begin(),
7792 PtrEnd = CandidateTypes[1].pointer_end();
7793 Ptr != PtrEnd; ++Ptr) {
7794 // Make sure we don't add the same candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007795 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007796 continue;
7797
Chandler Carruth8e543b32010-12-12 08:17:55 +00007798 QualType ParamTypes[2] = {
7799 S.Context.getLValueReferenceType(*Ptr),
7800 *Ptr,
7801 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007802
7803 // non-volatile version
Richard Smithe54c3072013-05-05 15:51:06 +00007804 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007805 /*IsAssigmentOperator=*/true);
7806
Douglas Gregor5bee2582012-06-04 00:15:09 +00007807 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7808 VisibleTypeConversionsQuals.hasVolatile();
7809 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007810 // volatile version
7811 ParamTypes[0] =
7812 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007813 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7814 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007815 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007816
7817 if (!(*Ptr).isRestrictQualified() &&
7818 VisibleTypeConversionsQuals.hasRestrict()) {
7819 // restrict version
7820 ParamTypes[0]
7821 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007822 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7823 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007824
7825 if (NeedVolatile) {
7826 // volatile restrict version
7827 ParamTypes[0]
7828 = S.Context.getLValueReferenceType(
7829 S.Context.getCVRQualifiedType(*Ptr,
7830 (Qualifiers::Volatile |
7831 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007832 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7833 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007834 }
7835 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007836 }
7837 }
7838 }
7839
7840 // C++ [over.built]p18:
7841 //
7842 // For every triple (L, VQ, R), where L is an arithmetic type,
7843 // VQ is either volatile or empty, and R is a promoted
7844 // arithmetic type, there exist candidate operator functions of
7845 // the form
7846 //
7847 // VQ L& operator=(VQ L&, R);
7848 // VQ L& operator*=(VQ L&, R);
7849 // VQ L& operator/=(VQ L&, R);
7850 // VQ L& operator+=(VQ L&, R);
7851 // VQ L& operator-=(VQ L&, R);
7852 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007853 if (!HasArithmeticOrEnumeralCandidateType)
7854 return;
7855
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007856 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7857 for (unsigned Right = FirstPromotedArithmeticType;
7858 Right < LastPromotedArithmeticType; ++Right) {
7859 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007860 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007861
7862 // Add this built-in operator as a candidate (VQ is empty).
7863 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007864 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007865 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007866 /*IsAssigmentOperator=*/isEqualOp);
7867
7868 // Add this built-in operator as a candidate (VQ is 'volatile').
7869 if (VisibleTypeConversionsQuals.hasVolatile()) {
7870 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007871 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007872 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007873 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007874 /*IsAssigmentOperator=*/isEqualOp);
7875 }
7876 }
7877 }
7878
7879 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7880 for (BuiltinCandidateTypeSet::iterator
7881 Vec1 = CandidateTypes[0].vector_begin(),
7882 Vec1End = CandidateTypes[0].vector_end();
7883 Vec1 != Vec1End; ++Vec1) {
7884 for (BuiltinCandidateTypeSet::iterator
7885 Vec2 = CandidateTypes[1].vector_begin(),
7886 Vec2End = CandidateTypes[1].vector_end();
7887 Vec2 != Vec2End; ++Vec2) {
7888 QualType ParamTypes[2];
7889 ParamTypes[1] = *Vec2;
7890 // Add this built-in operator as a candidate (VQ is empty).
7891 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smithe54c3072013-05-05 15:51:06 +00007892 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007893 /*IsAssigmentOperator=*/isEqualOp);
7894
7895 // Add this built-in operator as a candidate (VQ is 'volatile').
7896 if (VisibleTypeConversionsQuals.hasVolatile()) {
7897 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7898 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007899 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007900 /*IsAssigmentOperator=*/isEqualOp);
7901 }
7902 }
7903 }
7904 }
7905
7906 // C++ [over.built]p22:
7907 //
7908 // For every triple (L, VQ, R), where L is an integral type, VQ
7909 // is either volatile or empty, and R is a promoted integral
7910 // type, there exist candidate operator functions of the form
7911 //
7912 // VQ L& operator%=(VQ L&, R);
7913 // VQ L& operator<<=(VQ L&, R);
7914 // VQ L& operator>>=(VQ L&, R);
7915 // VQ L& operator&=(VQ L&, R);
7916 // VQ L& operator^=(VQ L&, R);
7917 // VQ L& operator|=(VQ L&, R);
7918 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007919 if (!HasArithmeticOrEnumeralCandidateType)
7920 return;
7921
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007922 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7923 for (unsigned Right = FirstPromotedIntegralType;
7924 Right < LastPromotedIntegralType; ++Right) {
7925 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007926 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007927
7928 // Add this built-in operator as a candidate (VQ is empty).
7929 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007930 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007931 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007932 if (VisibleTypeConversionsQuals.hasVolatile()) {
7933 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00007934 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007935 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7936 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007937 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007938 }
7939 }
7940 }
7941 }
7942
7943 // C++ [over.operator]p23:
7944 //
7945 // There also exist candidate operator functions of the form
7946 //
7947 // bool operator!(bool);
7948 // bool operator&&(bool, bool);
7949 // bool operator||(bool, bool);
7950 void addExclaimOverload() {
7951 QualType ParamTy = S.Context.BoolTy;
Richard Smithe54c3072013-05-05 15:51:06 +00007952 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007953 /*IsAssignmentOperator=*/false,
7954 /*NumContextualBoolArguments=*/1);
7955 }
7956 void addAmpAmpOrPipePipeOverload() {
7957 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007958 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007959 /*IsAssignmentOperator=*/false,
7960 /*NumContextualBoolArguments=*/2);
7961 }
7962
7963 // C++ [over.built]p13:
7964 //
7965 // For every cv-qualified or cv-unqualified object type T there
7966 // exist candidate operator functions of the form
7967 //
7968 // T* operator+(T*, ptrdiff_t); [ABOVE]
7969 // T& operator[](T*, ptrdiff_t);
7970 // T* operator-(T*, ptrdiff_t); [ABOVE]
7971 // T* operator+(ptrdiff_t, T*); [ABOVE]
7972 // T& operator[](ptrdiff_t, T*);
7973 void addSubscriptOverloads() {
7974 for (BuiltinCandidateTypeSet::iterator
7975 Ptr = CandidateTypes[0].pointer_begin(),
7976 PtrEnd = CandidateTypes[0].pointer_end();
7977 Ptr != PtrEnd; ++Ptr) {
7978 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7979 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007980 if (!PointeeType->isObjectType())
7981 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007982
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007983 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7984
7985 // T& operator[](T*, ptrdiff_t)
Richard Smithe54c3072013-05-05 15:51:06 +00007986 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007987 }
7988
7989 for (BuiltinCandidateTypeSet::iterator
7990 Ptr = CandidateTypes[1].pointer_begin(),
7991 PtrEnd = CandidateTypes[1].pointer_end();
7992 Ptr != PtrEnd; ++Ptr) {
7993 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7994 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007995 if (!PointeeType->isObjectType())
7996 continue;
7997
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007998 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7999
8000 // T& operator[](ptrdiff_t, T*)
Richard Smithe54c3072013-05-05 15:51:06 +00008001 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008002 }
8003 }
8004
8005 // C++ [over.built]p11:
8006 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8007 // C1 is the same type as C2 or is a derived class of C2, T is an object
8008 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8009 // there exist candidate operator functions of the form
8010 //
8011 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8012 //
8013 // where CV12 is the union of CV1 and CV2.
8014 void addArrowStarOverloads() {
8015 for (BuiltinCandidateTypeSet::iterator
8016 Ptr = CandidateTypes[0].pointer_begin(),
8017 PtrEnd = CandidateTypes[0].pointer_end();
8018 Ptr != PtrEnd; ++Ptr) {
8019 QualType C1Ty = (*Ptr);
8020 QualType C1;
8021 QualifierCollector Q1;
8022 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8023 if (!isa<RecordType>(C1))
8024 continue;
8025 // heuristic to reduce number of builtin candidates in the set.
8026 // Add volatile/restrict version only if there are conversions to a
8027 // volatile/restrict type.
8028 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8029 continue;
8030 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8031 continue;
8032 for (BuiltinCandidateTypeSet::iterator
8033 MemPtr = CandidateTypes[1].member_pointer_begin(),
8034 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8035 MemPtr != MemPtrEnd; ++MemPtr) {
8036 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8037 QualType C2 = QualType(mptr->getClass(), 0);
8038 C2 = C2.getUnqualifiedType();
8039 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
8040 break;
8041 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8042 // build CV12 T&
8043 QualType T = mptr->getPointeeType();
8044 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8045 T.isVolatileQualified())
8046 continue;
8047 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8048 T.isRestrictQualified())
8049 continue;
8050 T = Q1.apply(S.Context, T);
8051 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smithe54c3072013-05-05 15:51:06 +00008052 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008053 }
8054 }
8055 }
8056
8057 // Note that we don't consider the first argument, since it has been
8058 // contextually converted to bool long ago. The candidates below are
8059 // therefore added as binary.
8060 //
8061 // C++ [over.built]p25:
8062 // For every type T, where T is a pointer, pointer-to-member, or scoped
8063 // enumeration type, there exist candidate operator functions of the form
8064 //
8065 // T operator?(bool, T, T);
8066 //
8067 void addConditionalOperatorOverloads() {
8068 /// Set of (canonical) types that we've already handled.
8069 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8070
8071 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8072 for (BuiltinCandidateTypeSet::iterator
8073 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8074 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8075 Ptr != PtrEnd; ++Ptr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008076 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008077 continue;
8078
8079 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00008080 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008081 }
8082
8083 for (BuiltinCandidateTypeSet::iterator
8084 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8085 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8086 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008087 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008088 continue;
8089
8090 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00008091 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008092 }
8093
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008094 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008095 for (BuiltinCandidateTypeSet::iterator
8096 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8097 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8098 Enum != EnumEnd; ++Enum) {
8099 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8100 continue;
8101
David Blaikie82e95a32014-11-19 07:49:47 +00008102 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008103 continue;
8104
8105 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00008106 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008107 }
8108 }
8109 }
8110 }
8111};
8112
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008113} // end anonymous namespace
8114
8115/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8116/// operator overloads to the candidate set (C++ [over.built]), based
8117/// on the operator @p Op and the arguments given. For example, if the
8118/// operator is a binary '+', this routine might add "int
8119/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00008120void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8121 SourceLocation OpLoc,
8122 ArrayRef<Expr *> Args,
8123 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00008124 // Find all of the types that the arguments can convert to, but only
8125 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00008126 // that make use of these types. Also record whether we encounter non-record
8127 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00008128 Qualifiers VisibleTypeConversionsQuals;
8129 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00008130 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00008131 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00008132
8133 bool HasNonRecordCandidateType = false;
8134 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008135 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00008136 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Benjamin Kramer57dddd482015-02-17 21:55:18 +00008137 CandidateTypes.emplace_back(*this);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008138 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8139 OpLoc,
8140 true,
8141 (Op == OO_Exclaim ||
8142 Op == OO_AmpAmp ||
8143 Op == OO_PipePipe),
8144 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00008145 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8146 CandidateTypes[ArgIdx].hasNonRecordTypes();
8147 HasArithmeticOrEnumeralCandidateType =
8148 HasArithmeticOrEnumeralCandidateType ||
8149 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008150 }
Douglas Gregora11693b2008-11-12 17:17:38 +00008151
Chandler Carruth00a38332010-12-13 01:44:01 +00008152 // Exit early when no non-record types have been added to the candidate set
8153 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008154 //
8155 // We can't exit early for !, ||, or &&, since there we have always have
8156 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008157 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008158 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00008159 return;
8160
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008161 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008162 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008163 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00008164 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008165 CandidateTypes, CandidateSet);
8166
8167 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00008168 switch (Op) {
8169 case OO_None:
8170 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00008171 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00008172
Chandler Carruth5184de02010-12-12 08:51:33 +00008173 case OO_New:
8174 case OO_Delete:
8175 case OO_Array_New:
8176 case OO_Array_Delete:
8177 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00008178 llvm_unreachable(
8179 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00008180
8181 case OO_Comma:
8182 case OO_Arrow:
8183 // C++ [over.match.oper]p3:
8184 // -- For the operator ',', the unary operator '&', or the
8185 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00008186 break;
8187
8188 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008189 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008190 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00008191 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00008192
8193 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008194 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008195 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008196 } else {
8197 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8198 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8199 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008200 break;
8201
Chandler Carruth5184de02010-12-12 08:51:33 +00008202 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008203 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008204 OpBuilder.addUnaryStarPointerOverloads();
8205 else
8206 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8207 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008208
Chandler Carruth5184de02010-12-12 08:51:33 +00008209 case OO_Slash:
8210 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008211 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008212
8213 case OO_PlusPlus:
8214 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008215 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8216 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008217 break;
8218
Douglas Gregor84605ae2009-08-24 13:43:27 +00008219 case OO_EqualEqual:
8220 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008221 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008222 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008223
Douglas Gregora11693b2008-11-12 17:17:38 +00008224 case OO_Less:
8225 case OO_Greater:
8226 case OO_LessEqual:
8227 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008228 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008229 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8230 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008231
Douglas Gregora11693b2008-11-12 17:17:38 +00008232 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008233 case OO_Caret:
8234 case OO_Pipe:
8235 case OO_LessLess:
8236 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008237 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008238 break;
8239
Chandler Carruth5184de02010-12-12 08:51:33 +00008240 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008241 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008242 // C++ [over.match.oper]p3:
8243 // -- For the operator ',', the unary operator '&', or the
8244 // operator '->', the built-in candidates set is empty.
8245 break;
8246
8247 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8248 break;
8249
8250 case OO_Tilde:
8251 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8252 break;
8253
Douglas Gregora11693b2008-11-12 17:17:38 +00008254 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008255 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008256 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008257
8258 case OO_PlusEqual:
8259 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008260 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008261 // Fall through.
8262
8263 case OO_StarEqual:
8264 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008265 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008266 break;
8267
8268 case OO_PercentEqual:
8269 case OO_LessLessEqual:
8270 case OO_GreaterGreaterEqual:
8271 case OO_AmpEqual:
8272 case OO_CaretEqual:
8273 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008274 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008275 break;
8276
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008277 case OO_Exclaim:
8278 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008279 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008280
Douglas Gregora11693b2008-11-12 17:17:38 +00008281 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008282 case OO_PipePipe:
8283 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008284 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008285
8286 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008287 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008288 break;
8289
8290 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008291 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008292 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008293
8294 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008295 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008296 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8297 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008298 }
8299}
8300
Douglas Gregore254f902009-02-04 00:32:51 +00008301/// \brief Add function candidates found via argument-dependent lookup
8302/// to the set of overloading candidates.
8303///
8304/// This routine performs argument-dependent name lookup based on the
8305/// given function name (which may also be an operator name) and adds
8306/// all of the overload candidates found by ADL to the overload
8307/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008308void
Douglas Gregore254f902009-02-04 00:32:51 +00008309Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smith100b24a2014-04-17 01:52:14 +00008310 SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008311 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008312 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008313 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008314 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008315 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008316
John McCall91f61fc2010-01-26 06:04:06 +00008317 // FIXME: This approach for uniquing ADL results (and removing
8318 // redundant candidates from the set) relies on pointer-equality,
8319 // which means we need to key off the canonical decl. However,
8320 // always going back to the canonical decl might not get us the
8321 // right set of default arguments. What default arguments are
8322 // we supposed to consider on ADL candidates, anyway?
8323
Douglas Gregorcabea402009-09-22 15:41:20 +00008324 // FIXME: Pass in the explicit template arguments?
Richard Smith100b24a2014-04-17 01:52:14 +00008325 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008326
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008327 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008328 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8329 CandEnd = CandidateSet.end();
8330 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008331 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008332 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008333 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008334 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008335 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008336
8337 // For each of the ADL candidates we found, add it to the overload
8338 // set.
John McCall8fe68082010-01-26 07:16:45 +00008339 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008340 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008341 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008342 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008343 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008344
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008345 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8346 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008347 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008348 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008349 FoundDecl, ExplicitTemplateArgs,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00008350 Args, CandidateSet, PartialOverloading);
Douglas Gregor15448f82009-06-27 21:05:07 +00008351 }
Douglas Gregore254f902009-02-04 00:32:51 +00008352}
8353
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008354/// isBetterOverloadCandidate - Determines whether the first overload
8355/// candidate is a better candidate than the second (C++ 13.3.3p1).
Richard Smith17c00b42014-11-12 01:24:00 +00008356bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8357 const OverloadCandidate &Cand2,
8358 SourceLocation Loc,
8359 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008360 // Define viable functions to be better candidates than non-viable
8361 // functions.
8362 if (!Cand2.Viable)
8363 return Cand1.Viable;
8364 else if (!Cand1.Viable)
8365 return false;
8366
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008367 // C++ [over.match.best]p1:
8368 //
8369 // -- if F is a static member function, ICS1(F) is defined such
8370 // that ICS1(F) is neither better nor worse than ICS1(G) for
8371 // any function G, and, symmetrically, ICS1(G) is neither
8372 // better nor worse than ICS1(F).
8373 unsigned StartArg = 0;
8374 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8375 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008376
Douglas Gregord3cb3562009-07-07 23:38:56 +00008377 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008378 // A viable function F1 is defined to be a better function than another
8379 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008380 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00008381 unsigned NumArgs = Cand1.NumConversions;
8382 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008383 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008384 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00008385 switch (CompareImplicitConversionSequences(S,
8386 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008387 Cand2.Conversions[ArgIdx])) {
8388 case ImplicitConversionSequence::Better:
8389 // Cand1 has a better conversion sequence.
8390 HasBetterConversion = true;
8391 break;
8392
8393 case ImplicitConversionSequence::Worse:
8394 // Cand1 can't be better than Cand2.
8395 return false;
8396
8397 case ImplicitConversionSequence::Indistinguishable:
8398 // Do nothing.
8399 break;
8400 }
8401 }
8402
Mike Stump11289f42009-09-09 15:08:12 +00008403 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008404 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008405 if (HasBetterConversion)
8406 return true;
8407
Douglas Gregora1f013e2008-11-07 22:36:19 +00008408 // -- the context is an initialization by user-defined conversion
8409 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8410 // from the return type of F1 to the destination type (i.e.,
8411 // the type of the entity being initialized) is a better
8412 // conversion sequence than the standard conversion sequence
8413 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00008414 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00008415 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00008416 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00008417 // First check whether we prefer one of the conversion functions over the
8418 // other. This only distinguishes the results in non-standard, extension
8419 // cases such as the conversion from a lambda closure type to a function
8420 // pointer or block.
Richard Smithec2748a2014-05-17 04:36:39 +00008421 ImplicitConversionSequence::CompareKind Result =
8422 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8423 if (Result == ImplicitConversionSequence::Indistinguishable)
8424 Result = CompareStandardConversionSequences(S,
8425 Cand1.FinalConversion,
8426 Cand2.FinalConversion);
Richard Smith6fdeaab2014-05-17 01:58:45 +00008427
Richard Smithec2748a2014-05-17 04:36:39 +00008428 if (Result != ImplicitConversionSequence::Indistinguishable)
8429 return Result == ImplicitConversionSequence::Better;
Richard Smith6fdeaab2014-05-17 01:58:45 +00008430
8431 // FIXME: Compare kind of reference binding if conversion functions
8432 // convert to a reference type used in direct reference binding, per
8433 // C++14 [over.match.best]p1 section 2 bullet 3.
8434 }
8435
8436 // -- F1 is a non-template function and F2 is a function template
8437 // specialization, or, if not that,
8438 bool Cand1IsSpecialization = Cand1.Function &&
8439 Cand1.Function->getPrimaryTemplate();
8440 bool Cand2IsSpecialization = Cand2.Function &&
8441 Cand2.Function->getPrimaryTemplate();
8442 if (Cand1IsSpecialization != Cand2IsSpecialization)
8443 return Cand2IsSpecialization;
8444
8445 // -- F1 and F2 are function template specializations, and the function
8446 // template for F1 is more specialized than the template for F2
8447 // according to the partial ordering rules described in 14.5.5.2, or,
8448 // if not that,
8449 if (Cand1IsSpecialization && Cand2IsSpecialization) {
8450 if (FunctionTemplateDecl *BetterTemplate
8451 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8452 Cand2.Function->getPrimaryTemplate(),
8453 Loc,
8454 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8455 : TPOC_Call,
8456 Cand1.ExplicitCallArguments,
8457 Cand2.ExplicitCallArguments))
8458 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregora1f013e2008-11-07 22:36:19 +00008459 }
8460
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008461 // Check for enable_if value-based overload resolution.
8462 if (Cand1.Function && Cand2.Function &&
8463 (Cand1.Function->hasAttr<EnableIfAttr>() ||
8464 Cand2.Function->hasAttr<EnableIfAttr>())) {
8465 // FIXME: The next several lines are just
8466 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8467 // instead of reverse order which is how they're stored in the AST.
8468 AttrVec Cand1Attrs;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008469 if (Cand1.Function->hasAttrs()) {
8470 Cand1Attrs = Cand1.Function->getAttrs();
Richard Smith9516eee2014-05-17 02:21:47 +00008471 Cand1Attrs.erase(std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(),
8472 IsNotEnableIfAttr),
8473 Cand1Attrs.end());
8474 std::reverse(Cand1Attrs.begin(), Cand1Attrs.end());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008475 }
8476
8477 AttrVec Cand2Attrs;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008478 if (Cand2.Function->hasAttrs()) {
8479 Cand2Attrs = Cand2.Function->getAttrs();
Richard Smith9516eee2014-05-17 02:21:47 +00008480 Cand2Attrs.erase(std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(),
8481 IsNotEnableIfAttr),
8482 Cand2Attrs.end());
8483 std::reverse(Cand2Attrs.begin(), Cand2Attrs.end());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008484 }
Richard Smith9516eee2014-05-17 02:21:47 +00008485
8486 // Candidate 1 is better if it has strictly more attributes and
8487 // the common sequence is identical.
8488 if (Cand1Attrs.size() <= Cand2Attrs.size())
8489 return false;
8490
8491 auto Cand1I = Cand1Attrs.begin();
8492 for (auto &Cand2A : Cand2Attrs) {
8493 auto &Cand1A = *Cand1I++;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008494 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
Richard Smith9516eee2014-05-17 02:21:47 +00008495 cast<EnableIfAttr>(Cand1A)->getCond()->Profile(Cand1ID,
8496 S.getASTContext(), true);
8497 cast<EnableIfAttr>(Cand2A)->getCond()->Profile(Cand2ID,
8498 S.getASTContext(), true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00008499 if (Cand1ID != Cand2ID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008500 return false;
8501 }
Richard Smith9516eee2014-05-17 02:21:47 +00008502
8503 return true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008504 }
8505
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008506 return false;
8507}
8508
Mike Stump11289f42009-09-09 15:08:12 +00008509/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008510/// within an overload candidate set.
8511///
James Dennettffad8b72012-06-22 08:10:18 +00008512/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008513/// which overload resolution occurs.
8514///
James Dennettffad8b72012-06-22 08:10:18 +00008515/// \param Best If overload resolution was successful or found a deleted
8516/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008517///
8518/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00008519OverloadingResult
8520OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008521 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00008522 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008523 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00008524 Best = end();
8525 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8526 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008527 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008528 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008529 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008530 }
8531
8532 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00008533 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008534 return OR_No_Viable_Function;
8535
8536 // Make sure that this function is better than every other viable
8537 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00008538 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00008539 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008540 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008541 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008542 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00008543 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008544 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00008545 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008546 }
Mike Stump11289f42009-09-09 15:08:12 +00008547
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008548 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00008549 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008550 (Best->Function->isDeleted() ||
8551 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00008552 return OR_Deleted;
8553
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008554 return OR_Success;
8555}
8556
John McCall53262c92010-01-12 02:15:36 +00008557namespace {
8558
8559enum OverloadCandidateKind {
8560 oc_function,
8561 oc_method,
8562 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00008563 oc_function_template,
8564 oc_method_template,
8565 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00008566 oc_implicit_default_constructor,
8567 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008568 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00008569 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008570 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00008571 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00008572};
8573
John McCalle1ac8d12010-01-13 00:25:19 +00008574OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8575 FunctionDecl *Fn,
8576 std::string &Description) {
8577 bool isTemplate = false;
8578
8579 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8580 isTemplate = true;
8581 Description = S.getTemplateArgumentBindingsText(
8582 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8583 }
John McCallfd0b2f82010-01-06 09:43:14 +00008584
8585 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00008586 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008587 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008588
Sebastian Redl08905022011-02-05 19:23:19 +00008589 if (Ctor->getInheritedConstructor())
8590 return oc_implicit_inherited_constructor;
8591
Alexis Hunt119c10e2011-05-25 23:16:36 +00008592 if (Ctor->isDefaultConstructor())
8593 return oc_implicit_default_constructor;
8594
8595 if (Ctor->isMoveConstructor())
8596 return oc_implicit_move_constructor;
8597
8598 assert(Ctor->isCopyConstructor() &&
8599 "unexpected sort of implicit constructor");
8600 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008601 }
8602
8603 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8604 // This actually gets spelled 'candidate function' for now, but
8605 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00008606 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008607 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00008608
Alexis Hunt119c10e2011-05-25 23:16:36 +00008609 if (Meth->isMoveAssignmentOperator())
8610 return oc_implicit_move_assignment;
8611
Douglas Gregor12695102012-02-10 08:36:38 +00008612 if (Meth->isCopyAssignmentOperator())
8613 return oc_implicit_copy_assignment;
8614
8615 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8616 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00008617 }
8618
John McCalle1ac8d12010-01-13 00:25:19 +00008619 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00008620}
8621
Larisse Voufo98b20f12013-07-19 23:00:19 +00008622void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
Sebastian Redl08905022011-02-05 19:23:19 +00008623 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8624 if (!Ctor) return;
8625
8626 Ctor = Ctor->getInheritedConstructor();
8627 if (!Ctor) return;
8628
8629 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8630}
8631
John McCall53262c92010-01-12 02:15:36 +00008632} // end anonymous namespace
8633
8634// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00008635void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00008636 std::string FnDesc;
8637 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00008638 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8639 << (unsigned) K << FnDesc;
8640 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8641 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00008642 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00008643}
8644
Nick Lewyckyed4265c2013-09-22 10:06:01 +00008645// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00008646// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00008647void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008648 assert(OverloadedExpr->getType() == Context.OverloadTy);
8649
8650 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8651 OverloadExpr *OvlExpr = Ovl.Expression;
8652
8653 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8654 IEnd = OvlExpr->decls_end();
8655 I != IEnd; ++I) {
8656 if (FunctionTemplateDecl *FunTmpl =
8657 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00008658 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008659 } else if (FunctionDecl *Fun
8660 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00008661 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008662 }
8663 }
8664}
8665
John McCall0d1da222010-01-12 00:44:57 +00008666/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8667/// "lead" diagnostic; it will be given two arguments, the source and
8668/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00008669void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8670 Sema &S,
8671 SourceLocation CaretLoc,
8672 const PartialDiagnostic &PDiag) const {
8673 S.Diag(CaretLoc, PDiag)
8674 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008675 // FIXME: The note limiting machinery is borrowed from
8676 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8677 // refactoring here.
8678 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8679 unsigned CandsShown = 0;
8680 AmbiguousConversionSequence::const_iterator I, E;
8681 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8682 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8683 break;
8684 ++CandsShown;
John McCall5c32be02010-08-24 20:38:10 +00008685 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00008686 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008687 if (I != E)
8688 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00008689}
8690
Richard Smith17c00b42014-11-12 01:24:00 +00008691static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
8692 unsigned I) {
John McCall6a61b522010-01-13 09:16:55 +00008693 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8694 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00008695 assert(Cand->Function && "for now, candidate must be a function");
8696 FunctionDecl *Fn = Cand->Function;
8697
8698 // There's a conversion slot for the object argument if this is a
8699 // non-constructor method. Note that 'I' corresponds the
8700 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00008701 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00008702 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00008703 if (I == 0)
8704 isObjectArgument = true;
8705 else
8706 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00008707 }
8708
John McCalle1ac8d12010-01-13 00:25:19 +00008709 std::string FnDesc;
8710 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8711
John McCall6a61b522010-01-13 09:16:55 +00008712 Expr *FromExpr = Conv.Bad.FromExpr;
8713 QualType FromTy = Conv.Bad.getFromType();
8714 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00008715
John McCallfb7ad0f2010-02-02 02:42:52 +00008716 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00008717 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00008718 Expr *E = FromExpr->IgnoreParens();
8719 if (isa<UnaryOperator>(E))
8720 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00008721 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00008722
8723 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8724 << (unsigned) FnKind << FnDesc
8725 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8726 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008727 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00008728 return;
8729 }
8730
John McCall6d174642010-01-23 08:10:49 +00008731 // Do some hand-waving analysis to see if the non-viability is due
8732 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00008733 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8734 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8735 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8736 CToTy = RT->getPointeeType();
8737 else {
8738 // TODO: detect and diagnose the full richness of const mismatches.
8739 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8740 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8741 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8742 }
8743
8744 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8745 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00008746 Qualifiers FromQs = CFromTy.getQualifiers();
8747 Qualifiers ToQs = CToTy.getQualifiers();
8748
8749 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8750 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8751 << (unsigned) FnKind << FnDesc
8752 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8753 << FromTy
8754 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8755 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008756 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008757 return;
8758 }
8759
John McCall31168b02011-06-15 23:02:42 +00008760 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008761 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00008762 << (unsigned) FnKind << FnDesc
8763 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8764 << FromTy
8765 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8766 << (unsigned) isObjectArgument << I+1;
8767 MaybeEmitInheritedConstructorNote(S, Fn);
8768 return;
8769 }
8770
Douglas Gregoraec25842011-04-26 23:16:46 +00008771 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8772 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8773 << (unsigned) FnKind << FnDesc
8774 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8775 << FromTy
8776 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8777 << (unsigned) isObjectArgument << I+1;
8778 MaybeEmitInheritedConstructorNote(S, Fn);
8779 return;
8780 }
8781
John McCall47000992010-01-14 03:28:57 +00008782 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8783 assert(CVR && "unexpected qualifiers mismatch");
8784
8785 if (isObjectArgument) {
8786 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8787 << (unsigned) FnKind << FnDesc
8788 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8789 << FromTy << (CVR - 1);
8790 } else {
8791 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8792 << (unsigned) FnKind << FnDesc
8793 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8794 << FromTy << (CVR - 1) << I+1;
8795 }
Sebastian Redl08905022011-02-05 19:23:19 +00008796 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008797 return;
8798 }
8799
Sebastian Redla72462c2011-09-24 17:48:32 +00008800 // Special diagnostic for failure to convert an initializer list, since
8801 // telling the user that it has type void is not useful.
8802 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8803 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8804 << (unsigned) FnKind << FnDesc
8805 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8806 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8807 MaybeEmitInheritedConstructorNote(S, Fn);
8808 return;
8809 }
8810
John McCall6d174642010-01-23 08:10:49 +00008811 // Diagnose references or pointers to incomplete types differently,
8812 // since it's far from impossible that the incompleteness triggered
8813 // the failure.
8814 QualType TempFromTy = FromTy.getNonReferenceType();
8815 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8816 TempFromTy = PTy->getPointeeType();
8817 if (TempFromTy->isIncompleteType()) {
8818 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8819 << (unsigned) FnKind << FnDesc
8820 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8821 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008822 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00008823 return;
8824 }
8825
Douglas Gregor56f2e342010-06-30 23:01:39 +00008826 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008827 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008828 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8829 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8830 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8831 FromPtrTy->getPointeeType()) &&
8832 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8833 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008834 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00008835 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008836 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008837 }
8838 } else if (const ObjCObjectPointerType *FromPtrTy
8839 = FromTy->getAs<ObjCObjectPointerType>()) {
8840 if (const ObjCObjectPointerType *ToPtrTy
8841 = ToTy->getAs<ObjCObjectPointerType>())
8842 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8843 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8844 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8845 FromPtrTy->getPointeeType()) &&
8846 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008847 BaseToDerivedConversion = 2;
8848 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008849 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8850 !FromTy->isIncompleteType() &&
8851 !ToRefTy->getPointeeType()->isIncompleteType() &&
8852 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8853 BaseToDerivedConversion = 3;
8854 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8855 ToTy.getNonReferenceType().getCanonicalType() ==
8856 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008857 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8858 << (unsigned) FnKind << FnDesc
8859 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8860 << (unsigned) isObjectArgument << I + 1;
8861 MaybeEmitInheritedConstructorNote(S, Fn);
8862 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008863 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008864 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008865
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008866 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008867 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008868 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00008869 << (unsigned) FnKind << FnDesc
8870 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008871 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008872 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008873 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00008874 return;
8875 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008876
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00008877 if (isa<ObjCObjectPointerType>(CFromTy) &&
8878 isa<PointerType>(CToTy)) {
8879 Qualifiers FromQs = CFromTy.getQualifiers();
8880 Qualifiers ToQs = CToTy.getQualifiers();
8881 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8882 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8883 << (unsigned) FnKind << FnDesc
8884 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8885 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8886 MaybeEmitInheritedConstructorNote(S, Fn);
8887 return;
8888 }
8889 }
8890
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008891 // Emit the generic diagnostic and, optionally, add the hints to it.
8892 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8893 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00008894 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008895 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8896 << (unsigned) (Cand->Fix.Kind);
8897
8898 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00008899 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8900 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008901 FDiag << *HI;
8902 S.Diag(Fn->getLocation(), FDiag);
8903
Sebastian Redl08905022011-02-05 19:23:19 +00008904 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00008905}
8906
Larisse Voufo98b20f12013-07-19 23:00:19 +00008907/// Additional arity mismatch diagnosis specific to a function overload
8908/// candidates. This is not covered by the more general DiagnoseArityMismatch()
8909/// over a candidate in any candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00008910static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8911 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00008912 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00008913 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008914
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008915 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00008916 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008917 // right number of arguments, because only overloaded operators have
8918 // the weird behavior of overloading member and non-member functions.
8919 // Just don't report anything.
8920 if (Fn->isInvalidDecl() &&
8921 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008922 return true;
8923
8924 if (NumArgs < MinParams) {
8925 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8926 (Cand->FailureKind == ovl_fail_bad_deduction &&
8927 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8928 } else {
8929 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8930 (Cand->FailureKind == ovl_fail_bad_deduction &&
8931 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8932 }
8933
8934 return false;
8935}
8936
8937/// General arity mismatch diagnosis over a candidate in a candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00008938static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008939 assert(isa<FunctionDecl>(D) &&
8940 "The templated declaration should at least be a function"
8941 " when diagnosing bad template argument deduction due to too many"
8942 " or too few arguments");
8943
8944 FunctionDecl *Fn = cast<FunctionDecl>(D);
8945
8946 // TODO: treat calls to a missing default constructor as a special case
8947 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8948 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008949
John McCall6a61b522010-01-13 09:16:55 +00008950 // at least / at most / exactly
8951 unsigned mode, modeCount;
8952 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00008953 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
8954 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00008955 mode = 0; // "at least"
8956 else
8957 mode = 2; // "exactly"
8958 modeCount = MinParams;
8959 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00008960 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00008961 mode = 1; // "at most"
8962 else
8963 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00008964 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00008965 }
8966
8967 std::string Description;
8968 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8969
Richard Smith10ff50d2012-05-11 05:16:41 +00008970 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8971 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Craig Topperc3ec1492014-05-26 06:22:03 +00008972 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8973 << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smith10ff50d2012-05-11 05:16:41 +00008974 else
8975 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Craig Topperc3ec1492014-05-26 06:22:03 +00008976 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8977 << mode << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00008978 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008979}
8980
Larisse Voufo98b20f12013-07-19 23:00:19 +00008981/// Arity mismatch diagnosis specific to a function overload candidate.
Richard Smith17c00b42014-11-12 01:24:00 +00008982static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8983 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008984 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
8985 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
8986}
Larisse Voufo47c08452013-07-19 22:53:23 +00008987
Richard Smith17c00b42014-11-12 01:24:00 +00008988static TemplateDecl *getDescribedTemplate(Decl *Templated) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008989 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
8990 return FD->getDescribedFunctionTemplate();
8991 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
8992 return RD->getDescribedClassTemplate();
8993
8994 llvm_unreachable("Unsupported: Getting the described template declaration"
8995 " for bad deduction diagnosis");
8996}
8997
8998/// Diagnose a failed template-argument deduction.
Richard Smith17c00b42014-11-12 01:24:00 +00008999static void DiagnoseBadDeduction(Sema &S, Decl *Templated,
9000 DeductionFailureInfo &DeductionFailure,
9001 unsigned NumArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009002 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009003 NamedDecl *ParamD;
9004 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9005 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9006 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00009007 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00009008 case Sema::TDK_Success:
9009 llvm_unreachable("TDK_success while diagnosing bad deduction");
9010
9011 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00009012 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00009013 S.Diag(Templated->getLocation(),
9014 diag::note_ovl_candidate_incomplete_deduction)
9015 << ParamD->getDeclName();
9016 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00009017 return;
9018 }
9019
John McCall42d7d192010-08-05 09:05:08 +00009020 case Sema::TDK_Underqualified: {
9021 assert(ParamD && "no parameter found for bad qualifiers deduction result");
9022 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9023
Larisse Voufo98b20f12013-07-19 23:00:19 +00009024 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009025
9026 // Param will have been canonicalized, but it should just be a
9027 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00009028 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00009029 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00009030 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00009031 assert(S.Context.hasSameType(Param, NonCanonParam));
9032
9033 // Arg has also been canonicalized, but there's nothing we can do
9034 // about that. It also doesn't matter as much, because it won't
9035 // have any template parameters in it (because deduction isn't
9036 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00009037 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009038
Larisse Voufo98b20f12013-07-19 23:00:19 +00009039 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9040 << ParamD->getDeclName() << Arg << NonCanonParam;
9041 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall42d7d192010-08-05 09:05:08 +00009042 return;
9043 }
9044
9045 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009046 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009047 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009048 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009049 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009050 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009051 which = 1;
9052 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009053 which = 2;
9054 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009055
Larisse Voufo98b20f12013-07-19 23:00:19 +00009056 S.Diag(Templated->getLocation(),
9057 diag::note_ovl_candidate_inconsistent_deduction)
9058 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9059 << *DeductionFailure.getSecondArg();
9060 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009061 return;
9062 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00009063
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009064 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009065 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009066 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00009067 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009068 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009069 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009070 else {
9071 int index = 0;
9072 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9073 index = TTP->getIndex();
9074 else if (NonTypeTemplateParmDecl *NTTP
9075 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9076 index = NTTP->getIndex();
9077 else
9078 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00009079 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009080 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009081 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009082 }
Larisse Voufo98b20f12013-07-19 23:00:19 +00009083 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009084 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009085
Douglas Gregor02eb4832010-05-08 18:13:28 +00009086 case Sema::TDK_TooManyArguments:
9087 case Sema::TDK_TooFewArguments:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009088 DiagnoseArityMismatch(S, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00009089 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00009090
9091 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009092 S.Diag(Templated->getLocation(),
9093 diag::note_ovl_candidate_instantiation_depth);
9094 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00009095 return;
9096
9097 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00009098 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009099 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009100 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00009101 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00009102 TemplateArgString = " ";
9103 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00009104 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00009105 }
9106
Richard Smith6f8d2c62012-05-09 05:17:00 +00009107 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009108 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009109 if (PDiag && PDiag->second.getDiagID() ==
9110 diag::err_typename_nested_not_found_enable_if) {
9111 // FIXME: Use the source range of the condition, and the fully-qualified
9112 // name of the enable_if template. These are both present in PDiag.
9113 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9114 << "'enable_if'" << TemplateArgString;
9115 return;
9116 }
9117
Richard Smith9ca64612012-05-07 09:03:25 +00009118 // Format the SFINAE diagnostic into the argument string.
9119 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9120 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009121 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009122 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009123 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00009124 SFINAEArgString = ": ";
9125 R = SourceRange(PDiag->first, PDiag->first);
9126 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9127 }
9128
Larisse Voufo98b20f12013-07-19 23:00:19 +00009129 S.Diag(Templated->getLocation(),
9130 diag::note_ovl_candidate_substitution_failure)
9131 << TemplateArgString << SFINAEArgString << R;
9132 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00009133 return;
9134 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009135
Richard Smith8c6eeb92013-01-31 04:03:12 +00009136 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009137 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9138 S.Diag(Templated->getLocation(),
Richard Smith8c6eeb92013-01-31 04:03:12 +00009139 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009140 << R.Expression->getName();
Richard Smith8c6eeb92013-01-31 04:03:12 +00009141 return;
9142 }
9143
Richard Trieue3732352013-04-08 21:11:40 +00009144 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00009145 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009146 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9147 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00009148 if (FirstTA.getKind() == TemplateArgument::Template &&
9149 SecondTA.getKind() == TemplateArgument::Template) {
9150 TemplateName FirstTN = FirstTA.getAsTemplate();
9151 TemplateName SecondTN = SecondTA.getAsTemplate();
9152 if (FirstTN.getKind() == TemplateName::Template &&
9153 SecondTN.getKind() == TemplateName::Template) {
9154 if (FirstTN.getAsTemplateDecl()->getName() ==
9155 SecondTN.getAsTemplateDecl()->getName()) {
9156 // FIXME: This fixes a bad diagnostic where both templates are named
9157 // the same. This particular case is a bit difficult since:
9158 // 1) It is passed as a string to the diagnostic printer.
9159 // 2) The diagnostic printer only attempts to find a better
9160 // name for types, not decls.
9161 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009162 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +00009163 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9164 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9165 return;
9166 }
9167 }
9168 }
Faisal Vali2b391ab2013-09-26 19:54:12 +00009169 // FIXME: For generic lambda parameters, check if the function is a lambda
9170 // call operator, and if so, emit a prettier and more informative
9171 // diagnostic that mentions 'auto' and lambda in addition to
9172 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009173 S.Diag(Templated->getLocation(),
9174 diag::note_ovl_candidate_non_deduced_mismatch)
9175 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +00009176 return;
Richard Trieue3732352013-04-08 21:11:40 +00009177 }
John McCall8b9ed552010-02-01 18:53:26 +00009178 // TODO: diagnose these individually, then kill off
9179 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +00009180 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009181 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9182 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00009183 return;
9184 }
9185}
9186
Larisse Voufo98b20f12013-07-19 23:00:19 +00009187/// Diagnose a failed template-argument deduction, for function calls.
Richard Smith17c00b42014-11-12 01:24:00 +00009188static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
9189 unsigned NumArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009190 unsigned TDK = Cand->DeductionFailure.Result;
9191 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9192 if (CheckArityMismatch(S, Cand, NumArgs))
9193 return;
9194 }
9195 DiagnoseBadDeduction(S, Cand->Function, // pattern
9196 Cand->DeductionFailure, NumArgs);
9197}
9198
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009199/// CUDA: diagnose an invalid call across targets.
Richard Smith17c00b42014-11-12 01:24:00 +00009200static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009201 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9202 FunctionDecl *Callee = Cand->Function;
9203
9204 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9205 CalleeTarget = S.IdentifyCUDATarget(Callee);
9206
9207 std::string FnDesc;
9208 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
9209
9210 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009211 << (unsigned)FnKind << CalleeTarget << CallerTarget;
9212
9213 // This could be an implicit constructor for which we could not infer the
9214 // target due to a collsion. Diagnose that case.
9215 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9216 if (Meth != nullptr && Meth->isImplicit()) {
9217 CXXRecordDecl *ParentClass = Meth->getParent();
9218 Sema::CXXSpecialMember CSM;
9219
9220 switch (FnKind) {
9221 default:
9222 return;
9223 case oc_implicit_default_constructor:
9224 CSM = Sema::CXXDefaultConstructor;
9225 break;
9226 case oc_implicit_copy_constructor:
9227 CSM = Sema::CXXCopyConstructor;
9228 break;
9229 case oc_implicit_move_constructor:
9230 CSM = Sema::CXXMoveConstructor;
9231 break;
9232 case oc_implicit_copy_assignment:
9233 CSM = Sema::CXXCopyAssignment;
9234 break;
9235 case oc_implicit_move_assignment:
9236 CSM = Sema::CXXMoveAssignment;
9237 break;
9238 };
9239
9240 bool ConstRHS = false;
9241 if (Meth->getNumParams()) {
9242 if (const ReferenceType *RT =
9243 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9244 ConstRHS = RT->getPointeeType().isConstQualified();
9245 }
9246 }
9247
9248 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9249 /* ConstRHS */ ConstRHS,
9250 /* Diagnose */ true);
9251 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009252}
9253
Richard Smith17c00b42014-11-12 01:24:00 +00009254static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009255 FunctionDecl *Callee = Cand->Function;
9256 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9257
9258 S.Diag(Callee->getLocation(),
9259 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9260 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9261}
9262
John McCall8b9ed552010-02-01 18:53:26 +00009263/// Generates a 'note' diagnostic for an overload candidate. We've
9264/// already generated a primary error at the call site.
9265///
9266/// It really does need to be a single diagnostic with its caret
9267/// pointed at the candidate declaration. Yes, this creates some
9268/// major challenges of technical writing. Yes, this makes pointing
9269/// out problems with specific arguments quite awkward. It's still
9270/// better than generating twenty screens of text for every failed
9271/// overload.
9272///
9273/// It would be great to be able to express per-candidate problems
9274/// more richly for those diagnostic clients that cared, but we'd
9275/// still have to be just as careful with the default diagnostics.
Richard Smith17c00b42014-11-12 01:24:00 +00009276static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
9277 unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00009278 FunctionDecl *Fn = Cand->Function;
9279
John McCall12f97bc2010-01-08 04:41:39 +00009280 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009281 if (Cand->Viable && (Fn->isDeleted() ||
9282 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00009283 std::string FnDesc;
9284 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00009285
9286 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00009287 << FnKind << FnDesc
9288 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redl08905022011-02-05 19:23:19 +00009289 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00009290 return;
John McCall12f97bc2010-01-08 04:41:39 +00009291 }
9292
John McCalle1ac8d12010-01-13 00:25:19 +00009293 // We don't really have anything else to say about viable candidates.
9294 if (Cand->Viable) {
9295 S.NoteOverloadCandidate(Fn);
9296 return;
9297 }
John McCall0d1da222010-01-12 00:44:57 +00009298
John McCall6a61b522010-01-13 09:16:55 +00009299 switch (Cand->FailureKind) {
9300 case ovl_fail_too_many_arguments:
9301 case ovl_fail_too_few_arguments:
9302 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00009303
John McCall6a61b522010-01-13 09:16:55 +00009304 case ovl_fail_bad_deduction:
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009305 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall8b9ed552010-02-01 18:53:26 +00009306
John McCall578a1f82014-12-14 01:46:53 +00009307 case ovl_fail_illegal_constructor: {
9308 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9309 << (Fn->getPrimaryTemplate() ? 1 : 0);
9310 MaybeEmitInheritedConstructorNote(S, Fn);
9311 return;
9312 }
9313
John McCallfe796dd2010-01-23 05:17:32 +00009314 case ovl_fail_trivial_conversion:
9315 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00009316 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00009317 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009318
John McCall65eb8792010-02-25 01:37:24 +00009319 case ovl_fail_bad_conversion: {
9320 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009321 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00009322 if (Cand->Conversions[I].isBad())
9323 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009324
John McCall6a61b522010-01-13 09:16:55 +00009325 // FIXME: this currently happens when we're called from SemaInit
9326 // when user-conversion overload fails. Figure out how to handle
9327 // those conditions and diagnose them well.
9328 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009329 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009330
9331 case ovl_fail_bad_target:
9332 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009333
9334 case ovl_fail_enable_if:
9335 return DiagnoseFailedEnableIfAttr(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00009336 }
John McCalld3224162010-01-08 00:58:21 +00009337}
9338
Richard Smith17c00b42014-11-12 01:24:00 +00009339static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
John McCalld3224162010-01-08 00:58:21 +00009340 // Desugar the type of the surrogate down to a function type,
9341 // retaining as many typedefs as possible while still showing
9342 // the function type (and, therefore, its parameter types).
9343 QualType FnType = Cand->Surrogate->getConversionType();
9344 bool isLValueReference = false;
9345 bool isRValueReference = false;
9346 bool isPointer = false;
9347 if (const LValueReferenceType *FnTypeRef =
9348 FnType->getAs<LValueReferenceType>()) {
9349 FnType = FnTypeRef->getPointeeType();
9350 isLValueReference = true;
9351 } else if (const RValueReferenceType *FnTypeRef =
9352 FnType->getAs<RValueReferenceType>()) {
9353 FnType = FnTypeRef->getPointeeType();
9354 isRValueReference = true;
9355 }
9356 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9357 FnType = FnTypePtr->getPointeeType();
9358 isPointer = true;
9359 }
9360 // Desugar down to a function type.
9361 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9362 // Reconstruct the pointer/reference as appropriate.
9363 if (isPointer) FnType = S.Context.getPointerType(FnType);
9364 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9365 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9366
9367 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9368 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00009369 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00009370}
9371
Richard Smith17c00b42014-11-12 01:24:00 +00009372static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9373 SourceLocation OpLoc,
9374 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009375 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00009376 std::string TypeStr("operator");
9377 TypeStr += Opc;
9378 TypeStr += "(";
9379 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00009380 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00009381 TypeStr += ")";
9382 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9383 } else {
9384 TypeStr += ", ";
9385 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9386 TypeStr += ")";
9387 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9388 }
9389}
9390
Richard Smith17c00b42014-11-12 01:24:00 +00009391static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9392 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009393 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00009394 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9395 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00009396 if (ICS.isBad()) break; // all meaningless after first invalid
9397 if (!ICS.isAmbiguous()) continue;
9398
John McCall5c32be02010-08-24 20:38:10 +00009399 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00009400 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00009401 }
9402}
9403
Larisse Voufo98b20f12013-07-19 23:00:19 +00009404static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +00009405 if (Cand->Function)
9406 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00009407 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00009408 return Cand->Surrogate->getLocation();
9409 return SourceLocation();
9410}
9411
Larisse Voufo98b20f12013-07-19 23:00:19 +00009412static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00009413 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009414 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00009415 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009416
Douglas Gregorc5c01a62012-09-13 21:01:57 +00009417 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009418 case Sema::TDK_Incomplete:
9419 return 1;
9420
9421 case Sema::TDK_Underqualified:
9422 case Sema::TDK_Inconsistent:
9423 return 2;
9424
9425 case Sema::TDK_SubstitutionFailure:
9426 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +00009427 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009428 return 3;
9429
9430 case Sema::TDK_InstantiationDepth:
9431 case Sema::TDK_FailedOverloadResolution:
9432 return 4;
9433
9434 case Sema::TDK_InvalidExplicitArguments:
9435 return 5;
9436
9437 case Sema::TDK_TooManyArguments:
9438 case Sema::TDK_TooFewArguments:
9439 return 6;
9440 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009441 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009442}
9443
Richard Smith17c00b42014-11-12 01:24:00 +00009444namespace {
John McCallad2587a2010-01-12 00:48:53 +00009445struct CompareOverloadCandidatesForDisplay {
9446 Sema &S;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009447 size_t NumArgs;
9448
9449 CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs)
9450 : S(S), NumArgs(nArgs) {}
John McCall12f97bc2010-01-08 04:41:39 +00009451
9452 bool operator()(const OverloadCandidate *L,
9453 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00009454 // Fast-path this check.
9455 if (L == R) return false;
9456
John McCall12f97bc2010-01-08 04:41:39 +00009457 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00009458 if (L->Viable) {
9459 if (!R->Viable) return true;
9460
9461 // TODO: introduce a tri-valued comparison for overload
9462 // candidates. Would be more worthwhile if we had a sort
9463 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00009464 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9465 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00009466 } else if (R->Viable)
9467 return false;
John McCall12f97bc2010-01-08 04:41:39 +00009468
John McCall3712d9e2010-01-15 23:32:50 +00009469 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00009470
John McCall3712d9e2010-01-15 23:32:50 +00009471 // Criteria by which we can sort non-viable candidates:
9472 if (!L->Viable) {
9473 // 1. Arity mismatches come after other candidates.
9474 if (L->FailureKind == ovl_fail_too_many_arguments ||
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009475 L->FailureKind == ovl_fail_too_few_arguments) {
9476 if (R->FailureKind == ovl_fail_too_many_arguments ||
9477 R->FailureKind == ovl_fail_too_few_arguments) {
Kaelyn Takata50c4ffc2014-05-07 00:43:38 +00009478 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9479 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9480 if (LDist == RDist) {
9481 if (L->FailureKind == R->FailureKind)
9482 // Sort non-surrogates before surrogates.
9483 return !L->IsSurrogate && R->IsSurrogate;
9484 // Sort candidates requiring fewer parameters than there were
9485 // arguments given after candidates requiring more parameters
9486 // than there were arguments given.
9487 return L->FailureKind == ovl_fail_too_many_arguments;
9488 }
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009489 return LDist < RDist;
9490 }
John McCall3712d9e2010-01-15 23:32:50 +00009491 return false;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009492 }
John McCall3712d9e2010-01-15 23:32:50 +00009493 if (R->FailureKind == ovl_fail_too_many_arguments ||
9494 R->FailureKind == ovl_fail_too_few_arguments)
9495 return true;
John McCall12f97bc2010-01-08 04:41:39 +00009496
John McCallfe796dd2010-01-23 05:17:32 +00009497 // 2. Bad conversions come first and are ordered by the number
9498 // of bad conversions and quality of good conversions.
9499 if (L->FailureKind == ovl_fail_bad_conversion) {
9500 if (R->FailureKind != ovl_fail_bad_conversion)
9501 return true;
9502
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009503 // The conversion that can be fixed with a smaller number of changes,
9504 // comes first.
9505 unsigned numLFixes = L->Fix.NumConversionsFixed;
9506 unsigned numRFixes = R->Fix.NumConversionsFixed;
9507 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9508 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009509 if (numLFixes != numRFixes) {
David Blaikie7a3cbb22015-03-09 02:02:07 +00009510 return numLFixes < numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009511 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009512
John McCallfe796dd2010-01-23 05:17:32 +00009513 // If there's any ordering between the defined conversions...
9514 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00009515 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00009516
9517 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00009518 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009519 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00009520 switch (CompareImplicitConversionSequences(S,
9521 L->Conversions[I],
9522 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00009523 case ImplicitConversionSequence::Better:
9524 leftBetter++;
9525 break;
9526
9527 case ImplicitConversionSequence::Worse:
9528 leftBetter--;
9529 break;
9530
9531 case ImplicitConversionSequence::Indistinguishable:
9532 break;
9533 }
9534 }
9535 if (leftBetter > 0) return true;
9536 if (leftBetter < 0) return false;
9537
9538 } else if (R->FailureKind == ovl_fail_bad_conversion)
9539 return false;
9540
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009541 if (L->FailureKind == ovl_fail_bad_deduction) {
9542 if (R->FailureKind != ovl_fail_bad_deduction)
9543 return true;
9544
9545 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9546 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00009547 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00009548 } else if (R->FailureKind == ovl_fail_bad_deduction)
9549 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009550
John McCall3712d9e2010-01-15 23:32:50 +00009551 // TODO: others?
9552 }
9553
9554 // Sort everything else by location.
9555 SourceLocation LLoc = GetLocationForCandidate(L);
9556 SourceLocation RLoc = GetLocationForCandidate(R);
9557
9558 // Put candidates without locations (e.g. builtins) at the end.
9559 if (LLoc.isInvalid()) return false;
9560 if (RLoc.isInvalid()) return true;
9561
9562 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00009563 }
9564};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009565}
John McCall12f97bc2010-01-08 04:41:39 +00009566
John McCallfe796dd2010-01-23 05:17:32 +00009567/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009568/// computes up to the first. Produces the FixIt set if possible.
Richard Smith17c00b42014-11-12 01:24:00 +00009569static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9570 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00009571 assert(!Cand->Viable);
9572
9573 // Don't do anything on failures other than bad conversion.
9574 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9575
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009576 // We only want the FixIts if all the arguments can be corrected.
9577 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00009578 // Use a implicit copy initialization to check conversion fixes.
9579 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009580
John McCallfe796dd2010-01-23 05:17:32 +00009581 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00009582 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009583 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00009584 while (true) {
9585 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9586 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009587 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00009588 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00009589 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009590 }
John McCallfe796dd2010-01-23 05:17:32 +00009591 }
9592
9593 if (ConvIdx == ConvCount)
9594 return;
9595
John McCall65eb8792010-02-25 01:37:24 +00009596 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9597 "remaining conversion is initialized?");
9598
Douglas Gregoradc7a702010-04-16 17:45:54 +00009599 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00009600 // operation somehow.
9601 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00009602
9603 const FunctionProtoType* Proto;
9604 unsigned ArgIdx = ConvIdx;
9605
9606 if (Cand->IsSurrogate) {
9607 QualType ConvType
9608 = Cand->Surrogate->getConversionType().getNonReferenceType();
9609 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9610 ConvType = ConvPtrType->getPointeeType();
9611 Proto = ConvType->getAs<FunctionProtoType>();
9612 ArgIdx--;
9613 } else if (Cand->Function) {
9614 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9615 if (isa<CXXMethodDecl>(Cand->Function) &&
9616 !isa<CXXConstructorDecl>(Cand->Function))
9617 ArgIdx--;
9618 } else {
9619 // Builtin binary operator with a bad first conversion.
9620 assert(ConvCount <= 3);
9621 for (; ConvIdx != ConvCount; ++ConvIdx)
9622 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00009623 = TryCopyInitialization(S, Args[ConvIdx],
9624 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009625 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00009626 /*InOverloadResolution*/ true,
9627 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00009628 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00009629 return;
9630 }
9631
9632 // Fill in the rest of the conversions.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009633 unsigned NumParams = Proto->getNumParams();
John McCallfe796dd2010-01-23 05:17:32 +00009634 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009635 if (ArgIdx < NumParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009636 Cand->Conversions[ConvIdx] = TryCopyInitialization(
9637 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
9638 /*InOverloadResolution=*/true,
9639 /*AllowObjCWritebackConversion=*/
9640 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009641 // Store the FixIt in the candidate if it exists.
9642 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00009643 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009644 }
John McCallfe796dd2010-01-23 05:17:32 +00009645 else
9646 Cand->Conversions[ConvIdx].setEllipsis();
9647 }
9648}
9649
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009650/// PrintOverloadCandidates - When overload resolution fails, prints
9651/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00009652/// set.
John McCall5c32be02010-08-24 20:38:10 +00009653void OverloadCandidateSet::NoteCandidates(Sema &S,
9654 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009655 ArrayRef<Expr *> Args,
David Blaikie1d202a62012-10-08 01:11:04 +00009656 StringRef Opc,
John McCall5c32be02010-08-24 20:38:10 +00009657 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00009658 // Sort the candidates by viability and position. Sorting directly would
9659 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009660 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00009661 if (OCD == OCD_AllCandidates) Cands.reserve(size());
9662 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00009663 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00009664 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00009665 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009666 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009667 if (Cand->Function || Cand->IsSurrogate)
9668 Cands.push_back(Cand);
9669 // Otherwise, this a non-viable builtin candidate. We do not, in general,
9670 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00009671 }
9672 }
9673
John McCallad2587a2010-01-12 00:48:53 +00009674 std::sort(Cands.begin(), Cands.end(),
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009675 CompareOverloadCandidatesForDisplay(S, Args.size()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009676
John McCall0d1da222010-01-12 00:44:57 +00009677 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00009678
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009679 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +00009680 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009681 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00009682 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9683 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00009684
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009685 // Set an arbitrary limit on the number of candidate functions we'll spam
9686 // the user with. FIXME: This limit should depend on details of the
9687 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +00009688 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009689 break;
9690 }
9691 ++CandsShown;
9692
John McCalld3224162010-01-08 00:58:21 +00009693 if (Cand->Function)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009694 NoteFunctionCandidate(S, Cand, Args.size());
John McCalld3224162010-01-08 00:58:21 +00009695 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00009696 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009697 else {
9698 assert(Cand->Viable &&
9699 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00009700 // Generally we only see ambiguities including viable builtin
9701 // operators if overload resolution got screwed up by an
9702 // ambiguous user-defined conversion.
9703 //
9704 // FIXME: It's quite possible for different conversions to see
9705 // different ambiguities, though.
9706 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00009707 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00009708 ReportedAmbiguousConversions = true;
9709 }
John McCalld3224162010-01-08 00:58:21 +00009710
John McCall0d1da222010-01-12 00:44:57 +00009711 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00009712 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00009713 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009714 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009715
9716 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00009717 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009718}
9719
Larisse Voufo98b20f12013-07-19 23:00:19 +00009720static SourceLocation
9721GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9722 return Cand->Specialization ? Cand->Specialization->getLocation()
9723 : SourceLocation();
9724}
9725
Richard Smith17c00b42014-11-12 01:24:00 +00009726namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009727struct CompareTemplateSpecCandidatesForDisplay {
9728 Sema &S;
9729 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9730
9731 bool operator()(const TemplateSpecCandidate *L,
9732 const TemplateSpecCandidate *R) {
9733 // Fast-path this check.
9734 if (L == R)
9735 return false;
9736
9737 // Assuming that both candidates are not matches...
9738
9739 // Sort by the ranking of deduction failures.
9740 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9741 return RankDeductionFailure(L->DeductionFailure) <
9742 RankDeductionFailure(R->DeductionFailure);
9743
9744 // Sort everything else by location.
9745 SourceLocation LLoc = GetLocationForCandidate(L);
9746 SourceLocation RLoc = GetLocationForCandidate(R);
9747
9748 // Put candidates without locations (e.g. builtins) at the end.
9749 if (LLoc.isInvalid())
9750 return false;
9751 if (RLoc.isInvalid())
9752 return true;
9753
9754 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9755 }
9756};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009757}
Larisse Voufo98b20f12013-07-19 23:00:19 +00009758
9759/// Diagnose a template argument deduction failure.
9760/// We are treating these failures as overload failures due to bad
9761/// deductions.
9762void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9763 DiagnoseBadDeduction(S, Specialization, // pattern
9764 DeductionFailure, /*NumArgs=*/0);
9765}
9766
9767void TemplateSpecCandidateSet::destroyCandidates() {
9768 for (iterator i = begin(), e = end(); i != e; ++i) {
9769 i->DeductionFailure.Destroy();
9770 }
9771}
9772
9773void TemplateSpecCandidateSet::clear() {
9774 destroyCandidates();
9775 Candidates.clear();
9776}
9777
9778/// NoteCandidates - When no template specialization match is found, prints
9779/// diagnostic messages containing the non-matching specializations that form
9780/// the candidate set.
9781/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9782/// OCD == OCD_AllCandidates and Cand->Viable == false.
9783void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9784 // Sort the candidates by position (assuming no candidate is a match).
9785 // Sorting directly would be prohibitive, so we make a set of pointers
9786 // and sort those.
9787 SmallVector<TemplateSpecCandidate *, 32> Cands;
9788 Cands.reserve(size());
9789 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9790 if (Cand->Specialization)
9791 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +00009792 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +00009793 // in general, want to list every possible builtin candidate.
9794 }
9795
9796 std::sort(Cands.begin(), Cands.end(),
9797 CompareTemplateSpecCandidatesForDisplay(S));
9798
9799 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9800 // for generalization purposes (?).
9801 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9802
9803 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9804 unsigned CandsShown = 0;
9805 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9806 TemplateSpecCandidate *Cand = *I;
9807
9808 // Set an arbitrary limit on the number of candidates we'll spam
9809 // the user with. FIXME: This limit should depend on details of the
9810 // candidate list.
9811 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9812 break;
9813 ++CandsShown;
9814
9815 assert(Cand->Specialization &&
9816 "Non-matching built-in candidates are not added to Cands.");
9817 Cand->NoteDeductionFailure(S);
9818 }
9819
9820 if (I != E)
9821 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9822}
9823
Douglas Gregorb491ed32011-02-19 21:32:49 +00009824// [PossiblyAFunctionType] --> [Return]
9825// NonFunctionType --> NonFunctionType
9826// R (A) --> R(A)
9827// R (*)(A) --> R (A)
9828// R (&)(A) --> R (A)
9829// R (S::*)(A) --> R (A)
9830QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9831 QualType Ret = PossiblyAFunctionType;
9832 if (const PointerType *ToTypePtr =
9833 PossiblyAFunctionType->getAs<PointerType>())
9834 Ret = ToTypePtr->getPointeeType();
9835 else if (const ReferenceType *ToTypeRef =
9836 PossiblyAFunctionType->getAs<ReferenceType>())
9837 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009838 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00009839 PossiblyAFunctionType->getAs<MemberPointerType>())
9840 Ret = MemTypePtr->getPointeeType();
9841 Ret =
9842 Context.getCanonicalType(Ret).getUnqualifiedType();
9843 return Ret;
9844}
Douglas Gregorcd695e52008-11-10 20:40:00 +00009845
Richard Smith17c00b42014-11-12 01:24:00 +00009846namespace {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009847// A helper class to help with address of function resolution
9848// - allows us to avoid passing around all those ugly parameters
Richard Smith17c00b42014-11-12 01:24:00 +00009849class AddressOfFunctionResolver {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009850 Sema& S;
9851 Expr* SourceExpr;
9852 const QualType& TargetType;
9853 QualType TargetFunctionType; // Extracted function type from target type
9854
9855 bool Complain;
9856 //DeclAccessPair& ResultFunctionAccessPair;
9857 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009858
Douglas Gregorb491ed32011-02-19 21:32:49 +00009859 bool TargetTypeIsNonStaticMemberFunction;
9860 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +00009861 bool StaticMemberFunctionFromBoundPointer;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009862
Douglas Gregorb491ed32011-02-19 21:32:49 +00009863 OverloadExpr::FindResult OvlExprInfo;
9864 OverloadExpr *OvlExpr;
9865 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009866 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009867 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009868
Douglas Gregorb491ed32011-02-19 21:32:49 +00009869public:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009870 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9871 const QualType &TargetType, bool Complain)
9872 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9873 Complain(Complain), Context(S.getASTContext()),
9874 TargetTypeIsNonStaticMemberFunction(
9875 !!TargetType->getAs<MemberPointerType>()),
9876 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +00009877 StaticMemberFunctionFromBoundPointer(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +00009878 OvlExprInfo(OverloadExpr::find(SourceExpr)),
9879 OvlExpr(OvlExprInfo.Expression),
9880 FailedCandidates(OvlExpr->getNameLoc()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009881 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +00009882
David Majnemera4f7c7a2013-08-01 06:13:59 +00009883 if (TargetFunctionType->isFunctionType()) {
9884 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9885 if (!UME->isImplicitAccess() &&
9886 !S.ResolveSingleFunctionTemplateSpecialization(UME))
9887 StaticMemberFunctionFromBoundPointer = true;
9888 } else if (OvlExpr->hasExplicitTemplateArgs()) {
9889 DeclAccessPair dap;
9890 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9891 OvlExpr, false, &dap)) {
9892 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9893 if (!Method->isStatic()) {
9894 // If the target type is a non-function type and the function found
9895 // is a non-static member function, pretend as if that was the
9896 // target, it's the only possible type to end up with.
9897 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +00009898
David Majnemera4f7c7a2013-08-01 06:13:59 +00009899 // And skip adding the function if its not in the proper form.
9900 // We'll diagnose this due to an empty set of functions.
9901 if (!OvlExprInfo.HasFormOfMemberPointer)
9902 return;
Chandler Carruthffce2452011-03-29 08:08:18 +00009903 }
9904
David Majnemera4f7c7a2013-08-01 06:13:59 +00009905 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +00009906 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009907 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00009908 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009909
9910 if (OvlExpr->hasExplicitTemplateArgs())
9911 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00009912
Douglas Gregorb491ed32011-02-19 21:32:49 +00009913 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9914 // C++ [over.over]p4:
9915 // If more than one function is selected, [...]
9916 if (Matches.size() > 1) {
9917 if (FoundNonTemplateFunction)
9918 EliminateAllTemplateMatches();
9919 else
9920 EliminateAllExceptMostSpecializedTemplate();
9921 }
9922 }
9923 }
9924
9925private:
9926 bool isTargetTypeAFunction() const {
9927 return TargetFunctionType->isFunctionType();
9928 }
9929
9930 // [ToType] [Return]
9931
9932 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9933 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9934 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9935 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9936 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9937 }
9938
9939 // return true if any matching specializations were found
9940 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9941 const DeclAccessPair& CurAccessFunPair) {
9942 if (CXXMethodDecl *Method
9943 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9944 // Skip non-static function templates when converting to pointer, and
9945 // static when converting to member pointer.
9946 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9947 return false;
9948 }
9949 else if (TargetTypeIsNonStaticMemberFunction)
9950 return false;
9951
9952 // C++ [over.over]p2:
9953 // If the name is a function template, template argument deduction is
9954 // done (14.8.2.2), and if the argument deduction succeeds, the
9955 // resulting template argument list is used to generate a single
9956 // function template specialization, which is added to the set of
9957 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +00009958 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009959 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +00009960 if (Sema::TemplateDeductionResult Result
9961 = S.DeduceTemplateArguments(FunctionTemplate,
9962 &OvlExplicitTemplateArgs,
9963 TargetFunctionType, Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00009964 Info, /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009965 // Make a note of the failed deduction for diagnostics.
9966 FailedCandidates.addCandidate()
9967 .set(FunctionTemplate->getTemplatedDecl(),
9968 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +00009969 return false;
9970 }
9971
Douglas Gregor19a41f12013-04-17 08:45:07 +00009972 // Template argument deduction ensures that we have an exact match or
9973 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009974 // This function template specicalization works.
9975 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Douglas Gregor19a41f12013-04-17 08:45:07 +00009976 assert(S.isSameOrCompatibleFunctionType(
9977 Context.getCanonicalType(Specialization->getType()),
9978 Context.getCanonicalType(TargetFunctionType)));
Douglas Gregorb491ed32011-02-19 21:32:49 +00009979 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9980 return true;
9981 }
9982
9983 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9984 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009985 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009986 // Skip non-static functions when converting to pointer, and static
9987 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009988 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9989 return false;
9990 }
9991 else if (TargetTypeIsNonStaticMemberFunction)
9992 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009993
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009994 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009995 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009996 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009997 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl))
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009998 return false;
9999
Richard Smith2a7d4812013-05-04 07:00:32 +000010000 // If any candidate has a placeholder return type, trigger its deduction
10001 // now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +000010002 if (S.getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +000010003 FunDecl->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +000010004 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
10005 return false;
10006
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000010007 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010008 if (Context.hasSameUnqualifiedType(TargetFunctionType,
10009 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +000010010 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
10011 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010012 Matches.push_back(std::make_pair(CurAccessFunPair,
10013 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010014 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010015 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010016 }
Mike Stump11289f42009-09-09 15:08:12 +000010017 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010018
10019 return false;
10020 }
10021
10022 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10023 bool Ret = false;
10024
10025 // If the overload expression doesn't have the form of a pointer to
10026 // member, don't try to convert it to a pointer-to-member type.
10027 if (IsInvalidFormOfPointerToMemberFunction())
10028 return false;
10029
10030 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10031 E = OvlExpr->decls_end();
10032 I != E; ++I) {
10033 // Look through any using declarations to find the underlying function.
10034 NamedDecl *Fn = (*I)->getUnderlyingDecl();
10035
10036 // C++ [over.over]p3:
10037 // Non-member functions and static member functions match
10038 // targets of type "pointer-to-function" or "reference-to-function."
10039 // Nonstatic member functions match targets of
10040 // type "pointer-to-member-function."
10041 // Note that according to DR 247, the containing class does not matter.
10042 if (FunctionTemplateDecl *FunctionTemplate
10043 = dyn_cast<FunctionTemplateDecl>(Fn)) {
10044 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10045 Ret = true;
10046 }
10047 // If we have explicit template arguments supplied, skip non-templates.
10048 else if (!OvlExpr->hasExplicitTemplateArgs() &&
10049 AddMatchingNonTemplateFunction(Fn, I.getPair()))
10050 Ret = true;
10051 }
10052 assert(Ret || Matches.empty());
10053 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010054 }
10055
Douglas Gregorb491ed32011-02-19 21:32:49 +000010056 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +000010057 // [...] and any given function template specialization F1 is
10058 // eliminated if the set contains a second function template
10059 // specialization whose function template is more specialized
10060 // than the function template of F1 according to the partial
10061 // ordering rules of 14.5.5.2.
10062
10063 // The algorithm specified above is quadratic. We instead use a
10064 // two-pass algorithm (similar to the one used to identify the
10065 // best viable function in an overload set) that identifies the
10066 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +000010067
10068 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10069 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10070 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010071
Larisse Voufo98b20f12013-07-19 23:00:19 +000010072 // TODO: It looks like FailedCandidates does not serve much purpose
10073 // here, since the no_viable diagnostic has index 0.
10074 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +000010075 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010076 SourceExpr->getLocStart(), S.PDiag(),
10077 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
10078 .second->getDeclName(),
10079 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
10080 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010081
Douglas Gregorb491ed32011-02-19 21:32:49 +000010082 if (Result != MatchesCopy.end()) {
10083 // Make it the first and only element
10084 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10085 Matches[0].second = cast<FunctionDecl>(*Result);
10086 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +000010087 }
10088 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010089
Douglas Gregorb491ed32011-02-19 21:32:49 +000010090 void EliminateAllTemplateMatches() {
10091 // [...] any function template specializations in the set are
10092 // eliminated if the set also contains a non-template function, [...]
10093 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010094 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010095 ++I;
10096 else {
10097 Matches[I] = Matches[--N];
10098 Matches.set_size(N);
10099 }
10100 }
10101 }
10102
10103public:
10104 void ComplainNoMatchesFound() const {
10105 assert(Matches.empty());
10106 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10107 << OvlExpr->getName() << TargetFunctionType
10108 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +000010109 if (FailedCandidates.empty())
10110 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
10111 else {
10112 // We have some deduction failure messages. Use them to diagnose
10113 // the function templates, and diagnose the non-template candidates
10114 // normally.
10115 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10116 IEnd = OvlExpr->decls_end();
10117 I != IEnd; ++I)
10118 if (FunctionDecl *Fun =
10119 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
10120 S.NoteOverloadCandidate(Fun, TargetFunctionType);
10121 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10122 }
10123 }
10124
Douglas Gregorb491ed32011-02-19 21:32:49 +000010125 bool IsInvalidFormOfPointerToMemberFunction() const {
10126 return TargetTypeIsNonStaticMemberFunction &&
10127 !OvlExprInfo.HasFormOfMemberPointer;
10128 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010129
Douglas Gregorb491ed32011-02-19 21:32:49 +000010130 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10131 // TODO: Should we condition this on whether any functions might
10132 // have matched, or is it more appropriate to do that in callers?
10133 // TODO: a fixit wouldn't hurt.
10134 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10135 << TargetType << OvlExpr->getSourceRange();
10136 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010137
10138 bool IsStaticMemberFunctionFromBoundPointer() const {
10139 return StaticMemberFunctionFromBoundPointer;
10140 }
10141
10142 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10143 S.Diag(OvlExpr->getLocStart(),
10144 diag::err_invalid_form_pointer_member_function)
10145 << OvlExpr->getSourceRange();
10146 }
10147
Douglas Gregorb491ed32011-02-19 21:32:49 +000010148 void ComplainOfInvalidConversion() const {
10149 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10150 << OvlExpr->getName() << TargetType;
10151 }
10152
10153 void ComplainMultipleMatchesFound() const {
10154 assert(Matches.size() > 1);
10155 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10156 << OvlExpr->getName()
10157 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +000010158 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010159 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010160
10161 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10162
Douglas Gregorb491ed32011-02-19 21:32:49 +000010163 int getNumMatches() const { return Matches.size(); }
10164
10165 FunctionDecl* getMatchingFunctionDecl() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010166 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010167 return Matches[0].second;
10168 }
10169
10170 const DeclAccessPair* getMatchingFunctionAccessPair() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010171 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010172 return &Matches[0].first;
10173 }
10174};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010175}
Richard Smith17c00b42014-11-12 01:24:00 +000010176
Douglas Gregorb491ed32011-02-19 21:32:49 +000010177/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10178/// an overloaded function (C++ [over.over]), where @p From is an
10179/// expression with overloaded function type and @p ToType is the type
10180/// we're trying to resolve to. For example:
10181///
10182/// @code
10183/// int f(double);
10184/// int f(int);
10185///
10186/// int (*pfd)(double) = f; // selects f(double)
10187/// @endcode
10188///
10189/// This routine returns the resulting FunctionDecl if it could be
10190/// resolved, and NULL otherwise. When @p Complain is true, this
10191/// routine will emit diagnostics if there is an error.
10192FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010193Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10194 QualType TargetType,
10195 bool Complain,
10196 DeclAccessPair &FoundResult,
10197 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010198 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010199
10200 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10201 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010202 int NumMatches = Resolver.getNumMatches();
Craig Topperc3ec1492014-05-26 06:22:03 +000010203 FunctionDecl *Fn = nullptr;
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010204 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010205 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10206 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10207 else
10208 Resolver.ComplainNoMatchesFound();
10209 }
10210 else if (NumMatches > 1 && Complain)
10211 Resolver.ComplainMultipleMatchesFound();
10212 else if (NumMatches == 1) {
10213 Fn = Resolver.getMatchingFunctionDecl();
10214 assert(Fn);
10215 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +000010216 if (Complain) {
10217 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10218 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10219 else
10220 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10221 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +000010222 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010223
10224 if (pHadMultipleCandidates)
10225 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010226 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010227}
10228
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010229/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010230/// resolve that overloaded function expression down to a single function.
10231///
10232/// This routine can only resolve template-ids that refer to a single function
10233/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010234/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010235/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +000010236///
10237/// If no template-ids are found, no diagnostics are emitted and NULL is
10238/// returned.
John McCall0009fcc2011-04-26 20:42:42 +000010239FunctionDecl *
10240Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10241 bool Complain,
10242 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010243 // C++ [over.over]p1:
10244 // [...] [Note: any redundant set of parentheses surrounding the
10245 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010246 // C++ [over.over]p1:
10247 // [...] The overloaded function name can be preceded by the &
10248 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010249
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010250 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +000010251 if (!ovl->hasExplicitTemplateArgs())
Craig Topperc3ec1492014-05-26 06:22:03 +000010252 return nullptr;
John McCall1acbbb52010-02-02 06:20:04 +000010253
10254 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +000010255 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010256 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010257
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010258 // Look through all of the overloaded functions, searching for one
10259 // whose type matches exactly.
Craig Topperc3ec1492014-05-26 06:22:03 +000010260 FunctionDecl *Matched = nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010261 for (UnresolvedSetIterator I = ovl->decls_begin(),
10262 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010263 // C++0x [temp.arg.explicit]p3:
10264 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010265 // where deduction is not done, if a template argument list is
10266 // specified and it, along with any default template arguments,
10267 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010268 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +000010269 FunctionTemplateDecl *FunctionTemplate
10270 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010271
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010272 // C++ [over.over]p2:
10273 // If the name is a function template, template argument deduction is
10274 // done (14.8.2.2), and if the argument deduction succeeds, the
10275 // resulting template argument list is used to generate a single
10276 // function template specialization, which is added to the set of
10277 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010278 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010279 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010280 if (TemplateDeductionResult Result
10281 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000010282 Specialization, Info,
10283 /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010284 // Make a note of the failed deduction for diagnostics.
10285 // TODO: Actually use the failed-deduction info?
10286 FailedCandidates.addCandidate()
10287 .set(FunctionTemplate->getTemplatedDecl(),
10288 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010289 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010290 }
10291
John McCall0009fcc2011-04-26 20:42:42 +000010292 assert(Specialization && "no specialization and no error?");
10293
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010294 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010295 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010296 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000010297 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10298 << ovl->getName();
10299 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010300 }
Craig Topperc3ec1492014-05-26 06:22:03 +000010301 return nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010302 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010303
John McCall0009fcc2011-04-26 20:42:42 +000010304 Matched = Specialization;
10305 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010306 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010307
Aaron Ballmandd69ef32014-08-19 15:55:55 +000010308 if (Matched && getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +000010309 Matched->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +000010310 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
Craig Topperc3ec1492014-05-26 06:22:03 +000010311 return nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +000010312
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010313 return Matched;
10314}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010315
Douglas Gregor1beec452011-03-12 01:48:56 +000010316
10317
10318
John McCall50a2c2c2011-10-11 23:14:30 +000010319// Resolve and fix an overloaded expression that can be resolved
10320// because it identifies a single function template specialization.
10321//
Douglas Gregor1beec452011-03-12 01:48:56 +000010322// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000010323//
10324// Return true if it was logically possible to so resolve the
10325// expression, regardless of whether or not it succeeded. Always
10326// returns true if 'complain' is set.
10327bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10328 ExprResult &SrcExpr, bool doFunctionPointerConverion,
10329 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +000010330 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000010331 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000010332 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000010333
John McCall50a2c2c2011-10-11 23:14:30 +000010334 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000010335
John McCall0009fcc2011-04-26 20:42:42 +000010336 DeclAccessPair found;
10337 ExprResult SingleFunctionExpression;
10338 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10339 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010340 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000010341 SrcExpr = ExprError();
10342 return true;
10343 }
John McCall0009fcc2011-04-26 20:42:42 +000010344
10345 // It is only correct to resolve to an instance method if we're
10346 // resolving a form that's permitted to be a pointer to member.
10347 // Otherwise we'll end up making a bound member expression, which
10348 // is illegal in all the contexts we resolve like this.
10349 if (!ovl.HasFormOfMemberPointer &&
10350 isa<CXXMethodDecl>(fn) &&
10351 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000010352 if (!complain) return false;
10353
10354 Diag(ovl.Expression->getExprLoc(),
10355 diag::err_bound_member_function)
10356 << 0 << ovl.Expression->getSourceRange();
10357
10358 // TODO: I believe we only end up here if there's a mix of
10359 // static and non-static candidates (otherwise the expression
10360 // would have 'bound member' type, not 'overload' type).
10361 // Ideally we would note which candidate was chosen and why
10362 // the static candidates were rejected.
10363 SrcExpr = ExprError();
10364 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010365 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010366
Sylvestre Ledrua5202662012-07-31 06:56:50 +000010367 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000010368 SingleFunctionExpression =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010369 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall0009fcc2011-04-26 20:42:42 +000010370
10371 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000010372 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000010373 SingleFunctionExpression =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010374 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall50a2c2c2011-10-11 23:14:30 +000010375 if (SingleFunctionExpression.isInvalid()) {
10376 SrcExpr = ExprError();
10377 return true;
10378 }
10379 }
John McCall0009fcc2011-04-26 20:42:42 +000010380 }
10381
10382 if (!SingleFunctionExpression.isUsable()) {
10383 if (complain) {
10384 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10385 << ovl.Expression->getName()
10386 << DestTypeForComplaining
10387 << OpRangeForComplaining
10388 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000010389 NoteAllOverloadCandidates(SrcExpr.get());
10390
10391 SrcExpr = ExprError();
10392 return true;
10393 }
10394
10395 return false;
John McCall0009fcc2011-04-26 20:42:42 +000010396 }
10397
John McCall50a2c2c2011-10-11 23:14:30 +000010398 SrcExpr = SingleFunctionExpression;
10399 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010400}
10401
Douglas Gregorcabea402009-09-22 15:41:20 +000010402/// \brief Add a single candidate to the overload set.
10403static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000010404 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000010405 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010406 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010407 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000010408 bool PartialOverloading,
10409 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000010410 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000010411 if (isa<UsingShadowDecl>(Callee))
10412 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10413
Douglas Gregorcabea402009-09-22 15:41:20 +000010414 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000010415 if (ExplicitTemplateArgs) {
10416 assert(!KnownValid && "Explicit template arguments?");
10417 return;
10418 }
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010419 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
10420 /*SuppressUsedConversions=*/false,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010421 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010422 return;
John McCalld14a8642009-11-21 08:51:07 +000010423 }
10424
10425 if (FunctionTemplateDecl *FuncTemplate
10426 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000010427 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010428 ExplicitTemplateArgs, Args, CandidateSet,
10429 /*SuppressUsedConversions=*/false,
10430 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +000010431 return;
10432 }
10433
Richard Smith95ce4f62011-06-26 22:19:54 +000010434 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000010435}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010436
Douglas Gregorcabea402009-09-22 15:41:20 +000010437/// \brief Add the overload candidates named by callee and/or found by argument
10438/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000010439void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010440 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010441 OverloadCandidateSet &CandidateSet,
10442 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000010443
10444#ifndef NDEBUG
10445 // Verify that ArgumentDependentLookup is consistent with the rules
10446 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000010447 //
Douglas Gregorcabea402009-09-22 15:41:20 +000010448 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10449 // and let Y be the lookup set produced by argument dependent
10450 // lookup (defined as follows). If X contains
10451 //
10452 // -- a declaration of a class member, or
10453 //
10454 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000010455 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000010456 //
10457 // -- a declaration that is neither a function or a function
10458 // template
10459 //
10460 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000010461
John McCall57500772009-12-16 12:17:52 +000010462 if (ULE->requiresADL()) {
10463 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10464 E = ULE->decls_end(); I != E; ++I) {
10465 assert(!(*I)->getDeclContext()->isRecord());
10466 assert(isa<UsingShadowDecl>(*I) ||
10467 !(*I)->getDeclContext()->isFunctionOrMethod());
10468 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000010469 }
10470 }
10471#endif
10472
John McCall57500772009-12-16 12:17:52 +000010473 // It would be nice to avoid this copy.
10474 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000010475 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000010476 if (ULE->hasExplicitTemplateArgs()) {
10477 ULE->copyTemplateArgumentsInto(TABuffer);
10478 ExplicitTemplateArgs = &TABuffer;
10479 }
10480
10481 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10482 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010483 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10484 CandidateSet, PartialOverloading,
10485 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000010486
John McCall57500772009-12-16 12:17:52 +000010487 if (ULE->requiresADL())
Richard Smith100b24a2014-04-17 01:52:14 +000010488 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010489 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000010490 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010491}
John McCalld681c392009-12-16 08:11:27 +000010492
Richard Smith0603bbb2013-06-12 22:56:54 +000010493/// Determine whether a declaration with the specified name could be moved into
10494/// a different namespace.
10495static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10496 switch (Name.getCXXOverloadedOperator()) {
10497 case OO_New: case OO_Array_New:
10498 case OO_Delete: case OO_Array_Delete:
10499 return false;
10500
10501 default:
10502 return true;
10503 }
10504}
10505
Richard Smith998a5912011-06-05 22:42:48 +000010506/// Attempt to recover from an ill-formed use of a non-dependent name in a
10507/// template, where the non-dependent name was declared after the template
10508/// was defined. This is common in code written for a compilers which do not
10509/// correctly implement two-stage name lookup.
10510///
10511/// Returns true if a viable candidate was found and a diagnostic was issued.
10512static bool
10513DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10514 const CXXScopeSpec &SS, LookupResult &R,
Richard Smith100b24a2014-04-17 01:52:14 +000010515 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smith998a5912011-06-05 22:42:48 +000010516 TemplateArgumentListInfo *ExplicitTemplateArgs,
Hans Wennborg64937c62015-06-11 21:21:57 +000010517 ArrayRef<Expr *> Args,
10518 bool *DoDiagnoseEmptyLookup = nullptr) {
Richard Smith998a5912011-06-05 22:42:48 +000010519 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10520 return false;
10521
10522 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000010523 if (DC->isTransparentContext())
10524 continue;
10525
Richard Smith998a5912011-06-05 22:42:48 +000010526 SemaRef.LookupQualifiedName(R, DC);
10527
10528 if (!R.empty()) {
10529 R.suppressDiagnostics();
10530
10531 if (isa<CXXRecordDecl>(DC)) {
10532 // Don't diagnose names we find in classes; we get much better
10533 // diagnostics for these from DiagnoseEmptyLookup.
10534 R.clear();
Hans Wennborg64937c62015-06-11 21:21:57 +000010535 if (DoDiagnoseEmptyLookup)
10536 *DoDiagnoseEmptyLookup = true;
Richard Smith998a5912011-06-05 22:42:48 +000010537 return false;
10538 }
10539
Richard Smith100b24a2014-04-17 01:52:14 +000010540 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smith998a5912011-06-05 22:42:48 +000010541 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10542 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010543 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000010544 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000010545
10546 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000010547 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000010548 // No viable functions. Don't bother the user with notes for functions
10549 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000010550 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000010551 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000010552 }
Richard Smith998a5912011-06-05 22:42:48 +000010553
10554 // Find the namespaces where ADL would have looked, and suggest
10555 // declaring the function there instead.
10556 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10557 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000010558 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000010559 AssociatedNamespaces,
10560 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000010561 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000010562 if (canBeDeclaredInNamespace(R.getLookupName())) {
10563 DeclContext *Std = SemaRef.getStdNamespace();
10564 for (Sema::AssociatedNamespaceSet::iterator
10565 it = AssociatedNamespaces.begin(),
10566 end = AssociatedNamespaces.end(); it != end; ++it) {
10567 // Never suggest declaring a function within namespace 'std'.
10568 if (Std && Std->Encloses(*it))
10569 continue;
Richard Smith21bae432012-12-22 02:46:14 +000010570
Richard Smith0603bbb2013-06-12 22:56:54 +000010571 // Never suggest declaring a function within a namespace with a
10572 // reserved name, like __gnu_cxx.
10573 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10574 if (NS &&
10575 NS->getQualifiedNameAsString().find("__") != std::string::npos)
10576 continue;
10577
10578 SuggestedNamespaces.insert(*it);
10579 }
Richard Smith998a5912011-06-05 22:42:48 +000010580 }
10581
10582 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10583 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000010584 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000010585 SemaRef.Diag(Best->Function->getLocation(),
10586 diag::note_not_found_by_two_phase_lookup)
10587 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000010588 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000010589 SemaRef.Diag(Best->Function->getLocation(),
10590 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000010591 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000010592 } else {
10593 // FIXME: It would be useful to list the associated namespaces here,
10594 // but the diagnostics infrastructure doesn't provide a way to produce
10595 // a localized representation of a list of items.
10596 SemaRef.Diag(Best->Function->getLocation(),
10597 diag::note_not_found_by_two_phase_lookup)
10598 << R.getLookupName() << 2;
10599 }
10600
10601 // Try to recover by calling this function.
10602 return true;
10603 }
10604
10605 R.clear();
10606 }
10607
10608 return false;
10609}
10610
10611/// Attempt to recover from ill-formed use of a non-dependent operator in a
10612/// template, where the non-dependent operator was declared after the template
10613/// was defined.
10614///
10615/// Returns true if a viable candidate was found and a diagnostic was issued.
10616static bool
10617DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10618 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010619 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000010620 DeclarationName OpName =
10621 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10622 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10623 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Richard Smith100b24a2014-04-17 01:52:14 +000010624 OverloadCandidateSet::CSK_Operator,
Craig Topperc3ec1492014-05-26 06:22:03 +000010625 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smith998a5912011-06-05 22:42:48 +000010626}
10627
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010628namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000010629class BuildRecoveryCallExprRAII {
10630 Sema &SemaRef;
10631public:
10632 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10633 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10634 SemaRef.IsBuildingRecoveryCallExpr = true;
10635 }
10636
10637 ~BuildRecoveryCallExprRAII() {
10638 SemaRef.IsBuildingRecoveryCallExpr = false;
10639 }
10640};
10641
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010642}
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010643
Kaelyn Takata89c881b2014-10-27 18:07:29 +000010644static std::unique_ptr<CorrectionCandidateCallback>
10645MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
10646 bool HasTemplateArgs, bool AllowTypoCorrection) {
10647 if (!AllowTypoCorrection)
10648 return llvm::make_unique<NoTypoCorrectionCCC>();
10649 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
10650 HasTemplateArgs, ME);
10651}
10652
John McCalld681c392009-12-16 08:11:27 +000010653/// Attempts to recover from a call where no functions were found.
10654///
10655/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000010656static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000010657BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000010658 UnresolvedLookupExpr *ULE,
10659 SourceLocation LParenLoc,
Craig Toppere3d2ecbe2014-06-28 23:22:33 +000010660 MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000010661 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010662 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000010663 // Do not try to recover if it is already building a recovery call.
10664 // This stops infinite loops for template instantiations like
10665 //
10666 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10667 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10668 //
10669 if (SemaRef.IsBuildingRecoveryCallExpr)
10670 return ExprError();
10671 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000010672
10673 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000010674 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000010675 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000010676
John McCall57500772009-12-16 12:17:52 +000010677 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000010678 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000010679 if (ULE->hasExplicitTemplateArgs()) {
10680 ULE->copyTemplateArgumentsInto(TABuffer);
10681 ExplicitTemplateArgs = &TABuffer;
10682 }
10683
John McCalld681c392009-12-16 08:11:27 +000010684 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10685 Sema::LookupOrdinaryName);
Hans Wennborg64937c62015-06-11 21:21:57 +000010686 bool DoDiagnoseEmptyLookup = EmptyLookup;
Richard Smith998a5912011-06-05 22:42:48 +000010687 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Richard Smith100b24a2014-04-17 01:52:14 +000010688 OverloadCandidateSet::CSK_Normal,
Hans Wennborg64937c62015-06-11 21:21:57 +000010689 ExplicitTemplateArgs, Args,
10690 &DoDiagnoseEmptyLookup) &&
10691 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
10692 S, SS, R,
10693 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
10694 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
10695 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000010696 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000010697
John McCall57500772009-12-16 12:17:52 +000010698 assert(!R.empty() && "lookup results empty despite recovery");
10699
10700 // Build an implicit member call if appropriate. Just drop the
10701 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000010702 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000010703 if ((*R.begin())->isCXXClassMember())
Aaron Ballman6924dcd2015-09-01 14:49:24 +000010704 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
10705 ExplicitTemplateArgs, S);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000010706 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000010707 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000010708 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000010709 else
10710 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10711
10712 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000010713 return ExprError();
John McCall57500772009-12-16 12:17:52 +000010714
10715 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000010716 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000010717 // end up here.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010718 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010719 MultiExprArg(Args.data(), Args.size()),
10720 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000010721}
Douglas Gregor4038cf42010-06-08 17:35:15 +000010722
Sam Panzer0f384432012-08-21 00:52:01 +000010723/// \brief Constructs and populates an OverloadedCandidateSet from
10724/// the given function.
10725/// \returns true when an the ExprResult output parameter has been set.
10726bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10727 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010728 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010729 SourceLocation RParenLoc,
10730 OverloadCandidateSet *CandidateSet,
10731 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000010732#ifndef NDEBUG
10733 if (ULE->requiresADL()) {
10734 // To do ADL, we must have found an unqualified name.
10735 assert(!ULE->getQualifier() && "qualified name with ADL");
10736
10737 // We don't perform ADL for implicit declarations of builtins.
10738 // Verify that this was correctly set up.
10739 FunctionDecl *F;
10740 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10741 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10742 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000010743 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010744
John McCall57500772009-12-16 12:17:52 +000010745 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010746 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000010747 }
John McCall57500772009-12-16 12:17:52 +000010748#endif
10749
John McCall4124c492011-10-17 18:40:02 +000010750 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010751 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000010752 *Result = ExprError();
10753 return true;
10754 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000010755
John McCall57500772009-12-16 12:17:52 +000010756 // Add the functions denoted by the callee to the set of candidate
10757 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010758 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000010759
Hans Wennborgb2747382015-06-12 21:23:23 +000010760 if (getLangOpts().MSVCCompat &&
10761 CurContext->isDependentContext() && !isSFINAEContext() &&
Hans Wennborg64937c62015-06-11 21:21:57 +000010762 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
10763
10764 OverloadCandidateSet::iterator Best;
10765 if (CandidateSet->empty() ||
10766 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
10767 OR_No_Viable_Function) {
10768 // In Microsoft mode, if we are inside a template class member function then
10769 // create a type dependent CallExpr. The goal is to postpone name lookup
10770 // to instantiation time to be able to search into type dependent base
10771 // classes.
10772 CallExpr *CE = new (Context) CallExpr(
10773 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010774 CE->setTypeDependent(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010775 *Result = CE;
Sam Panzer0f384432012-08-21 00:52:01 +000010776 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010777 }
Francois Pichetbcf64712011-09-07 00:14:57 +000010778 }
John McCalld681c392009-12-16 08:11:27 +000010779
Hans Wennborg64937c62015-06-11 21:21:57 +000010780 if (CandidateSet->empty())
10781 return false;
10782
John McCall4124c492011-10-17 18:40:02 +000010783 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000010784 return false;
10785}
John McCall4124c492011-10-17 18:40:02 +000010786
Sam Panzer0f384432012-08-21 00:52:01 +000010787/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10788/// the completed call expression. If overload resolution fails, emits
10789/// diagnostics and returns ExprError()
10790static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10791 UnresolvedLookupExpr *ULE,
10792 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010793 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010794 SourceLocation RParenLoc,
10795 Expr *ExecConfig,
10796 OverloadCandidateSet *CandidateSet,
10797 OverloadCandidateSet::iterator *Best,
10798 OverloadingResult OverloadResult,
10799 bool AllowTypoCorrection) {
10800 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010801 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010802 RParenLoc, /*EmptyLookup=*/true,
10803 AllowTypoCorrection);
10804
10805 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000010806 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000010807 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000010808 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000010809 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10810 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000010811 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010812 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10813 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000010814 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010815
Richard Smith998a5912011-06-05 22:42:48 +000010816 case OR_No_Viable_Function: {
10817 // Try to recover by looking for viable functions which the user might
10818 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000010819 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010820 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010821 /*EmptyLookup=*/false,
10822 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000010823 if (!Recovery.isInvalid())
10824 return Recovery;
10825
Sam Panzer0f384432012-08-21 00:52:01 +000010826 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010827 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +000010828 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010829 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010830 break;
Richard Smith998a5912011-06-05 22:42:48 +000010831 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010832
10833 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000010834 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000010835 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010836 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010837 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000010838
Sam Panzer0f384432012-08-21 00:52:01 +000010839 case OR_Deleted: {
10840 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10841 << (*Best)->Function->isDeleted()
10842 << ULE->getName()
10843 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10844 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010845 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000010846
Sam Panzer0f384432012-08-21 00:52:01 +000010847 // We emitted an error for the unvailable/deleted function call but keep
10848 // the call in the AST.
10849 FunctionDecl *FDecl = (*Best)->Function;
10850 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010851 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10852 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000010853 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010854 }
10855
Douglas Gregorb412e172010-07-25 18:17:45 +000010856 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000010857 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010858}
10859
Sam Panzer0f384432012-08-21 00:52:01 +000010860/// BuildOverloadedCallExpr - Given the call expression that calls Fn
10861/// (which eventually refers to the declaration Func) and the call
10862/// arguments Args/NumArgs, attempt to resolve the function call down
10863/// to a specific function. If overload resolution succeeds, returns
10864/// the call expression produced by overload resolution.
10865/// Otherwise, emits diagnostics and returns ExprError.
10866ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10867 UnresolvedLookupExpr *ULE,
10868 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010869 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010870 SourceLocation RParenLoc,
10871 Expr *ExecConfig,
10872 bool AllowTypoCorrection) {
Richard Smith100b24a2014-04-17 01:52:14 +000010873 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
10874 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000010875 ExprResult result;
10876
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010877 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10878 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000010879 return result;
10880
10881 OverloadCandidateSet::iterator Best;
10882 OverloadingResult OverloadResult =
10883 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10884
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010885 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010886 RParenLoc, ExecConfig, &CandidateSet,
10887 &Best, OverloadResult,
10888 AllowTypoCorrection);
10889}
10890
John McCall4c4c1df2010-01-26 03:27:55 +000010891static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000010892 return Functions.size() > 1 ||
10893 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10894}
10895
Douglas Gregor084d8552009-03-13 23:49:33 +000010896/// \brief Create a unary operation that may resolve to an overloaded
10897/// operator.
10898///
10899/// \param OpLoc The location of the operator itself (e.g., '*').
10900///
10901/// \param OpcIn The UnaryOperator::Opcode that describes this
10902/// operator.
10903///
James Dennett18348b62012-06-22 08:52:37 +000010904/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000010905/// considered by overload resolution. The caller needs to build this
10906/// set based on the context using, e.g.,
10907/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10908/// set should not contain any member functions; those will be added
10909/// by CreateOverloadedUnaryOp().
10910///
James Dennett91738ff2012-06-22 10:32:46 +000010911/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000010912ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +000010913Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10914 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +000010915 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010916 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +000010917
10918 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10919 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10920 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010921 // TODO: provide better source location info.
10922 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000010923
John McCall4124c492011-10-17 18:40:02 +000010924 if (checkPlaceholderForOverload(*this, Input))
10925 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010926
Craig Topperc3ec1492014-05-26 06:22:03 +000010927 Expr *Args[2] = { Input, nullptr };
Douglas Gregor084d8552009-03-13 23:49:33 +000010928 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000010929
Douglas Gregor084d8552009-03-13 23:49:33 +000010930 // For post-increment and post-decrement, add the implicit '0' as
10931 // the second argument, so that we know this is a post-increment or
10932 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000010933 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010934 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000010935 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10936 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000010937 NumArgs = 2;
10938 }
10939
Richard Smithe54c3072013-05-05 15:51:06 +000010940 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10941
Douglas Gregor084d8552009-03-13 23:49:33 +000010942 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000010943 if (Fns.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010944 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
10945 VK_RValue, OK_Ordinary, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010946
Craig Topperc3ec1492014-05-26 06:22:03 +000010947 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000010948 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000010949 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000010950 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010951 /*ADL*/ true, IsOverloaded(Fns),
10952 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010953 return new (Context)
10954 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
10955 VK_RValue, OpLoc, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000010956 }
10957
10958 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000010959 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor084d8552009-03-13 23:49:33 +000010960
10961 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010962 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010963
10964 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000010965 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010966
John McCall4c4c1df2010-01-26 03:27:55 +000010967 // Add candidates from ADL.
Richard Smith100b24a2014-04-17 01:52:14 +000010968 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
Craig Topperc3ec1492014-05-26 06:22:03 +000010969 /*ExplicitTemplateArgs*/nullptr,
10970 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000010971
Douglas Gregor084d8552009-03-13 23:49:33 +000010972 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000010973 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010974
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010975 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10976
Douglas Gregor084d8552009-03-13 23:49:33 +000010977 // Perform overload resolution.
10978 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010979 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010980 case OR_Success: {
10981 // We found a built-in operator or an overloaded operator.
10982 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000010983
Douglas Gregor084d8552009-03-13 23:49:33 +000010984 if (FnDecl) {
10985 // We matched an overloaded operator. Build a call to that
10986 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000010987
Douglas Gregor084d8552009-03-13 23:49:33 +000010988 // Convert the arguments.
10989 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010990 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000010991
John Wiegley01296292011-04-08 18:41:53 +000010992 ExprResult InputRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000010993 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000010994 Best->FoundDecl, Method);
10995 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000010996 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010997 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000010998 } else {
10999 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011000 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000011001 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011002 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000011003 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011004 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000011005 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000011006 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011007 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011008 Input = InputInit.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011009 }
11010
Douglas Gregor084d8552009-03-13 23:49:33 +000011011 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000011012 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011013 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011014 if (FnExpr.isInvalid())
11015 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000011016
Richard Smithc1564702013-11-15 02:58:23 +000011017 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011018 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011019 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11020 ResultTy = ResultTy.getNonLValueExprType(Context);
11021
Eli Friedman030eee42009-11-18 03:58:17 +000011022 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000011023 CallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011024 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Lang Hames5de91cc2012-10-02 04:45:10 +000011025 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000011026
Alp Toker314cc812014-01-25 16:55:45 +000011027 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000011028 return ExprError();
11029
John McCallb268a282010-08-23 23:25:46 +000011030 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000011031 } else {
11032 // We matched a built-in operator. Convert the arguments, then
11033 // break out so that we will build the appropriate built-in
11034 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011035 ExprResult InputRes =
11036 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11037 Best->Conversions[0], AA_Passing);
11038 if (InputRes.isInvalid())
11039 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011040 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011041 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000011042 }
John Wiegley01296292011-04-08 18:41:53 +000011043 }
11044
11045 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000011046 // This is an erroneous use of an operator which can be overloaded by
11047 // a non-member function. Check for non-member operators which were
11048 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011049 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000011050 // FIXME: Recover by calling the found function.
11051 return ExprError();
11052
John Wiegley01296292011-04-08 18:41:53 +000011053 // No viable function; fall through to handling this as a
11054 // built-in operator, which will produce an error message for us.
11055 break;
11056
11057 case OR_Ambiguous:
11058 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11059 << UnaryOperator::getOpcodeStr(Opc)
11060 << Input->getType()
11061 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011062 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000011063 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11064 return ExprError();
11065
11066 case OR_Deleted:
11067 Diag(OpLoc, diag::err_ovl_deleted_oper)
11068 << Best->Function->isDeleted()
11069 << UnaryOperator::getOpcodeStr(Opc)
11070 << getDeletedOrUnavailableSuffix(Best->Function)
11071 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011072 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011073 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011074 return ExprError();
11075 }
Douglas Gregor084d8552009-03-13 23:49:33 +000011076
11077 // Either we found no viable overloaded operator or we matched a
11078 // built-in operator. In either case, fall through to trying to
11079 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000011080 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000011081}
11082
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011083/// \brief Create a binary operation that may resolve to an overloaded
11084/// operator.
11085///
11086/// \param OpLoc The location of the operator itself (e.g., '+').
11087///
11088/// \param OpcIn The BinaryOperator::Opcode that describes this
11089/// operator.
11090///
James Dennett18348b62012-06-22 08:52:37 +000011091/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011092/// considered by overload resolution. The caller needs to build this
11093/// set based on the context using, e.g.,
11094/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11095/// set should not contain any member functions; those will be added
11096/// by CreateOverloadedBinOp().
11097///
11098/// \param LHS Left-hand argument.
11099/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000011100ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011101Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +000011102 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +000011103 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011104 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011105 Expr *Args[2] = { LHS, RHS };
Craig Topperc3ec1492014-05-26 06:22:03 +000011106 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011107
11108 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
11109 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11110 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11111
11112 // If either side is type-dependent, create an appropriate dependent
11113 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000011114 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000011115 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011116 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000011117 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000011118 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011119 return new (Context) BinaryOperator(
11120 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11121 OpLoc, FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011122
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011123 return new (Context) CompoundAssignOperator(
11124 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11125 Context.DependentTy, Context.DependentTy, OpLoc,
11126 FPFeatures.fp_contract);
Douglas Gregor5287f092009-11-05 00:51:44 +000011127 }
John McCall4c4c1df2010-01-26 03:27:55 +000011128
11129 // FIXME: save results of ADL from here?
Craig Topperc3ec1492014-05-26 06:22:03 +000011130 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011131 // TODO: provide better source location info in DNLoc component.
11132 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000011133 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000011134 = UnresolvedLookupExpr::Create(Context, NamingClass,
11135 NestedNameSpecifierLoc(), OpNameInfo,
11136 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011137 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011138 return new (Context)
11139 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11140 VK_RValue, OpLoc, FPFeatures.fp_contract);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011141 }
11142
John McCall4124c492011-10-17 18:40:02 +000011143 // Always do placeholder-like conversions on the RHS.
11144 if (checkPlaceholderForOverload(*this, Args[1]))
11145 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011146
John McCall526ab472011-10-25 17:37:35 +000011147 // Do placeholder-like conversion on the LHS; note that we should
11148 // not get here with a PseudoObject LHS.
11149 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000011150 if (checkPlaceholderForOverload(*this, Args[0]))
11151 return ExprError();
11152
Sebastian Redl6a96bf72009-11-18 23:10:33 +000011153 // If this is the assignment operator, we only perform overload resolution
11154 // if the left-hand side is a class or enumeration type. This is actually
11155 // a hack. The standard requires that we do overload resolution between the
11156 // various built-in candidates, but as DR507 points out, this can lead to
11157 // problems. So we do it this way, which pretty much follows what GCC does.
11158 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000011159 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000011160 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011161
John McCalle26a8722010-12-04 08:14:53 +000011162 // If this is the .* operator, which is not overloadable, just
11163 // create a built-in binary operator.
11164 if (Opc == BO_PtrMemD)
11165 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11166
Douglas Gregor084d8552009-03-13 23:49:33 +000011167 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011168 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011169
11170 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011171 AddFunctionCandidates(Fns, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011172
11173 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011174 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011175
Richard Smith0daabd72014-09-23 20:31:39 +000011176 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11177 // performed for an assignment operator (nor for operator[] nor operator->,
11178 // which don't get here).
11179 if (Opc != BO_Assign)
11180 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11181 /*ExplicitTemplateArgs*/ nullptr,
11182 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011183
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011184 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011185 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011186
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011187 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11188
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011189 // Perform overload resolution.
11190 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011191 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000011192 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011193 // We found a built-in operator or an overloaded operator.
11194 FunctionDecl *FnDecl = Best->Function;
11195
11196 if (FnDecl) {
11197 // We matched an overloaded operator. Build a call to that
11198 // operator.
11199
11200 // Convert the arguments.
11201 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000011202 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000011203 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011204
Chandler Carruth8e543b32010-12-12 08:17:55 +000011205 ExprResult Arg1 =
11206 PerformCopyInitialization(
11207 InitializedEntity::InitializeParameter(Context,
11208 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011209 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011210 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011211 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011212
John Wiegley01296292011-04-08 18:41:53 +000011213 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011214 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011215 Best->FoundDecl, Method);
11216 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011217 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011218 Args[0] = Arg0.getAs<Expr>();
11219 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011220 } else {
11221 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000011222 ExprResult Arg0 = PerformCopyInitialization(
11223 InitializedEntity::InitializeParameter(Context,
11224 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011225 SourceLocation(), Args[0]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011226 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011227 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011228
Chandler Carruth8e543b32010-12-12 08:17:55 +000011229 ExprResult Arg1 =
11230 PerformCopyInitialization(
11231 InitializedEntity::InitializeParameter(Context,
11232 FnDecl->getParamDecl(1)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011233 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011234 if (Arg1.isInvalid())
11235 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011236 Args[0] = LHS = Arg0.getAs<Expr>();
11237 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011238 }
11239
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011240 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011241 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011242 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011243 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011244 if (FnExpr.isInvalid())
11245 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011246
Richard Smithc1564702013-11-15 02:58:23 +000011247 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011248 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011249 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11250 ResultTy = ResultTy.getNonLValueExprType(Context);
11251
John McCallb268a282010-08-23 23:25:46 +000011252 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011253 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000011254 Args, ResultTy, VK, OpLoc,
11255 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011256
Alp Toker314cc812014-01-25 16:55:45 +000011257 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011258 FnDecl))
11259 return ExprError();
11260
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011261 ArrayRef<const Expr *> ArgsArray(Args, 2);
11262 // Cut off the implicit 'this'.
11263 if (isa<CXXMethodDecl>(FnDecl))
11264 ArgsArray = ArgsArray.slice(1);
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011265
11266 // Check for a self move.
11267 if (Op == OO_Equal)
11268 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11269
Douglas Gregorb4866e82015-06-19 18:13:19 +000011270 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011271 TheCall->getSourceRange(), VariadicDoesNotApply);
11272
John McCallb268a282010-08-23 23:25:46 +000011273 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011274 } else {
11275 // We matched a built-in operator. Convert the arguments, then
11276 // break out so that we will build the appropriate built-in
11277 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011278 ExprResult ArgsRes0 =
11279 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11280 Best->Conversions[0], AA_Passing);
11281 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011282 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011283 Args[0] = ArgsRes0.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011284
John Wiegley01296292011-04-08 18:41:53 +000011285 ExprResult ArgsRes1 =
11286 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11287 Best->Conversions[1], AA_Passing);
11288 if (ArgsRes1.isInvalid())
11289 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011290 Args[1] = ArgsRes1.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011291 break;
11292 }
11293 }
11294
Douglas Gregor66950a32009-09-30 21:46:01 +000011295 case OR_No_Viable_Function: {
11296 // C++ [over.match.oper]p9:
11297 // If the operator is the operator , [...] and there are no
11298 // viable functions, then the operator is assumed to be the
11299 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000011300 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000011301 break;
11302
Chandler Carruth8e543b32010-12-12 08:17:55 +000011303 // For class as left operand for assignment or compound assigment
11304 // operator do not fall through to handling in built-in, but report that
11305 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000011306 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011307 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000011308 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000011309 Diag(OpLoc, diag::err_ovl_no_viable_oper)
11310 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000011311 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000011312 if (Args[0]->getType()->isIncompleteType()) {
11313 Diag(OpLoc, diag::note_assign_lhs_incomplete)
11314 << Args[0]->getType()
11315 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11316 }
Douglas Gregor66950a32009-09-30 21:46:01 +000011317 } else {
Richard Smith998a5912011-06-05 22:42:48 +000011318 // This is an erroneous use of an operator which can be overloaded by
11319 // a non-member function. Check for non-member operators which were
11320 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011321 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000011322 // FIXME: Recover by calling the found function.
11323 return ExprError();
11324
Douglas Gregor66950a32009-09-30 21:46:01 +000011325 // No viable function; try to create a built-in operation, which will
11326 // produce an error. Then, show the non-viable candidates.
11327 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000011328 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011329 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000011330 "C++ binary operator overloading is missing candidates!");
11331 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011332 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011333 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011334 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000011335 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011336
11337 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011338 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011339 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000011340 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000011341 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011342 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011343 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011344 return ExprError();
11345
11346 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000011347 if (isImplicitlyDeleted(Best->Function)) {
11348 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11349 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000011350 << Context.getRecordType(Method->getParent())
11351 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000011352
Richard Smithde1a4872012-12-28 12:23:24 +000011353 // The user probably meant to call this special member. Just
11354 // explain why it's deleted.
11355 NoteDeletedFunction(Method);
11356 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000011357 } else {
11358 Diag(OpLoc, diag::err_ovl_deleted_oper)
11359 << Best->Function->isDeleted()
11360 << BinaryOperator::getOpcodeStr(Opc)
11361 << getDeletedOrUnavailableSuffix(Best->Function)
11362 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11363 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011364 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011365 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011366 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000011367 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011368
Douglas Gregor66950a32009-09-30 21:46:01 +000011369 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000011370 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011371}
11372
John McCalldadc5752010-08-24 06:29:42 +000011373ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000011374Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11375 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000011376 Expr *Base, Expr *Idx) {
11377 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000011378 DeclarationName OpName =
11379 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11380
11381 // If either side is type-dependent, create an appropriate dependent
11382 // expression.
11383 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11384
Craig Topperc3ec1492014-05-26 06:22:03 +000011385 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011386 // CHECKME: no 'operator' keyword?
11387 DeclarationNameInfo OpNameInfo(OpName, LLoc);
11388 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000011389 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011390 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011391 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011392 /*ADL*/ true, /*Overloaded*/ false,
11393 UnresolvedSetIterator(),
11394 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000011395 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000011396
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011397 return new (Context)
11398 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11399 Context.DependentTy, VK_RValue, RLoc, false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011400 }
11401
John McCall4124c492011-10-17 18:40:02 +000011402 // Handle placeholders on both operands.
11403 if (checkPlaceholderForOverload(*this, Args[0]))
11404 return ExprError();
11405 if (checkPlaceholderForOverload(*this, Args[1]))
11406 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011407
Sebastian Redladba46e2009-10-29 20:17:01 +000011408 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011409 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redladba46e2009-10-29 20:17:01 +000011410
11411 // Subscript can only be overloaded as a member function.
11412
11413 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011414 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011415
11416 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011417 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011418
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011419 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11420
Sebastian Redladba46e2009-10-29 20:17:01 +000011421 // Perform overload resolution.
11422 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011423 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000011424 case OR_Success: {
11425 // We found a built-in operator or an overloaded operator.
11426 FunctionDecl *FnDecl = Best->Function;
11427
11428 if (FnDecl) {
11429 // We matched an overloaded operator. Build a call to that
11430 // operator.
11431
John McCalla0296f72010-03-19 07:35:19 +000011432 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000011433
Sebastian Redladba46e2009-10-29 20:17:01 +000011434 // Convert the arguments.
11435 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000011436 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011437 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011438 Best->FoundDecl, Method);
11439 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011440 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011441 Args[0] = Arg0.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011442
Anders Carlssona68e51e2010-01-29 18:37:50 +000011443 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011444 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000011445 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011446 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000011447 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011448 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011449 Args[1]);
Anders Carlssona68e51e2010-01-29 18:37:50 +000011450 if (InputInit.isInvalid())
11451 return ExprError();
11452
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011453 Args[1] = InputInit.getAs<Expr>();
Anders Carlssona68e51e2010-01-29 18:37:50 +000011454
Sebastian Redladba46e2009-10-29 20:17:01 +000011455 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011456 DeclarationNameInfo OpLocInfo(OpName, LLoc);
11457 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011458 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011459 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011460 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011461 OpLocInfo.getLoc(),
11462 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011463 if (FnExpr.isInvalid())
11464 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011465
Richard Smithc1564702013-11-15 02:58:23 +000011466 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000011467 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011468 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11469 ResultTy = ResultTy.getNonLValueExprType(Context);
11470
John McCallb268a282010-08-23 23:25:46 +000011471 CXXOperatorCallExpr *TheCall =
11472 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011473 FnExpr.get(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000011474 ResultTy, VK, RLoc,
11475 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011476
Alp Toker314cc812014-01-25 16:55:45 +000011477 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000011478 return ExprError();
11479
John McCallb268a282010-08-23 23:25:46 +000011480 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000011481 } else {
11482 // We matched a built-in operator. Convert the arguments, then
11483 // break out so that we will build the appropriate built-in
11484 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011485 ExprResult ArgsRes0 =
11486 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11487 Best->Conversions[0], AA_Passing);
11488 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011489 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011490 Args[0] = ArgsRes0.get();
John Wiegley01296292011-04-08 18:41:53 +000011491
11492 ExprResult ArgsRes1 =
11493 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11494 Best->Conversions[1], AA_Passing);
11495 if (ArgsRes1.isInvalid())
11496 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011497 Args[1] = ArgsRes1.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011498
11499 break;
11500 }
11501 }
11502
11503 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000011504 if (CandidateSet.empty())
11505 Diag(LLoc, diag::err_ovl_no_oper)
11506 << Args[0]->getType() << /*subscript*/ 0
11507 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11508 else
11509 Diag(LLoc, diag::err_ovl_no_viable_subscript)
11510 << Args[0]->getType()
11511 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011512 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011513 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000011514 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011515 }
11516
11517 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011518 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011519 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000011520 << Args[0]->getType() << Args[1]->getType()
11521 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011522 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011523 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011524 return ExprError();
11525
11526 case OR_Deleted:
11527 Diag(LLoc, diag::err_ovl_deleted_oper)
11528 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011529 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000011530 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011531 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011532 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011533 return ExprError();
11534 }
11535
11536 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000011537 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011538}
11539
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011540/// BuildCallToMemberFunction - Build a call to a member
11541/// function. MemExpr is the expression that refers to the member
11542/// function (and includes the object parameter), Args/NumArgs are the
11543/// arguments to the function call (not including the object
11544/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000011545/// expression refers to a non-static member function or an overloaded
11546/// member function.
John McCalldadc5752010-08-24 06:29:42 +000011547ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000011548Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011549 SourceLocation LParenLoc,
11550 MultiExprArg Args,
11551 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000011552 assert(MemExprE->getType() == Context.BoundMemberTy ||
11553 MemExprE->getType() == Context.OverloadTy);
11554
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011555 // Dig out the member expression. This holds both the object
11556 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000011557 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011558
John McCall0009fcc2011-04-26 20:42:42 +000011559 // Determine whether this is a call to a pointer-to-member function.
11560 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11561 assert(op->getType() == Context.BoundMemberTy);
11562 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
11563
11564 QualType fnType =
11565 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11566
11567 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11568 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000011569 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000011570
11571 // Check that the object type isn't more qualified than the
11572 // member function we're calling.
11573 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11574
11575 QualType objectType = op->getLHS()->getType();
11576 if (op->getOpcode() == BO_PtrMemI)
11577 objectType = objectType->castAs<PointerType>()->getPointeeType();
11578 Qualifiers objectQuals = objectType.getQualifiers();
11579
11580 Qualifiers difference = objectQuals - funcQuals;
11581 difference.removeObjCGCAttr();
11582 difference.removeAddressSpace();
11583 if (difference) {
11584 std::string qualsString = difference.getAsString();
11585 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11586 << fnType.getUnqualifiedType()
11587 << qualsString
11588 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11589 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011590
John McCall0009fcc2011-04-26 20:42:42 +000011591 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011592 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000011593 resultType, valueKind, RParenLoc);
11594
Alp Toker314cc812014-01-25 16:55:45 +000011595 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +000011596 call, nullptr))
John McCall0009fcc2011-04-26 20:42:42 +000011597 return ExprError();
11598
Craig Topperc3ec1492014-05-26 06:22:03 +000011599 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000011600 return ExprError();
11601
Richard Trieu9be9c682013-06-22 02:30:38 +000011602 if (CheckOtherCall(call, proto))
11603 return ExprError();
11604
John McCall0009fcc2011-04-26 20:42:42 +000011605 return MaybeBindToTemporary(call);
11606 }
11607
David Majnemerced8bdf2015-02-25 17:36:15 +000011608 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
11609 return new (Context)
11610 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
11611
John McCall4124c492011-10-17 18:40:02 +000011612 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011613 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000011614 return ExprError();
11615
John McCall10eae182009-11-30 22:42:35 +000011616 MemberExpr *MemExpr;
Craig Topperc3ec1492014-05-26 06:22:03 +000011617 CXXMethodDecl *Method = nullptr;
11618 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
11619 NestedNameSpecifier *Qualifier = nullptr;
John McCall10eae182009-11-30 22:42:35 +000011620 if (isa<MemberExpr>(NakedMemExpr)) {
11621 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000011622 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000011623 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011624 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000011625 UnbridgedCasts.restore();
Nick Lewyckye283c552015-08-25 22:33:16 +000011626
11627 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
11628 Diag(MemExprE->getLocStart(),
11629 diag::err_ovl_no_viable_member_function_in_call)
11630 << Method << Method->getSourceRange();
11631 Diag(Method->getLocation(),
11632 diag::note_ovl_candidate_disabled_by_enable_if_attr)
11633 << Attr->getCond()->getSourceRange() << Attr->getMessage();
11634 return ExprError();
11635 }
John McCall10eae182009-11-30 22:42:35 +000011636 } else {
11637 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011638 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011639
John McCall6e9f8f62009-12-03 04:06:58 +000011640 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000011641 Expr::Classification ObjectClassification
11642 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11643 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000011644
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011645 // Add overload candidates
Richard Smith100b24a2014-04-17 01:52:14 +000011646 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
11647 OverloadCandidateSet::CSK_Normal);
Mike Stump11289f42009-09-09 15:08:12 +000011648
John McCall2d74de92009-12-01 22:10:20 +000011649 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000011650 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000011651 if (UnresExpr->hasExplicitTemplateArgs()) {
11652 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11653 TemplateArgs = &TemplateArgsBuffer;
11654 }
11655
John McCall10eae182009-11-30 22:42:35 +000011656 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11657 E = UnresExpr->decls_end(); I != E; ++I) {
11658
John McCall6e9f8f62009-12-03 04:06:58 +000011659 NamedDecl *Func = *I;
11660 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11661 if (isa<UsingShadowDecl>(Func))
11662 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11663
Douglas Gregor02824322011-01-26 19:30:28 +000011664
Francois Pichet64225792011-01-18 05:04:39 +000011665 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011666 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011667 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011668 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000011669 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000011670 // If explicit template arguments were provided, we can't call a
11671 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000011672 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000011673 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011674
John McCalla0296f72010-03-19 07:35:19 +000011675 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011676 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000011677 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000011678 } else {
John McCall10eae182009-11-30 22:42:35 +000011679 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000011680 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011681 ObjectType, ObjectClassification,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011682 Args, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000011683 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000011684 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000011685 }
Mike Stump11289f42009-09-09 15:08:12 +000011686
John McCall10eae182009-11-30 22:42:35 +000011687 DeclarationName DeclName = UnresExpr->getMemberName();
11688
John McCall4124c492011-10-17 18:40:02 +000011689 UnbridgedCasts.restore();
11690
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011691 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011692 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000011693 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011694 case OR_Success:
11695 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000011696 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000011697 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011698 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11699 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000011700 // If FoundDecl is different from Method (such as if one is a template
11701 // and the other a specialization), make sure DiagnoseUseOfDecl is
11702 // called on both.
11703 // FIXME: This would be more comprehensively addressed by modifying
11704 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11705 // being used.
11706 if (Method != FoundDecl.getDecl() &&
11707 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11708 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011709 break;
11710
11711 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000011712 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011713 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000011714 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011715 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011716 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011717 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011718
11719 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000011720 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000011721 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011722 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011723 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011724 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000011725
11726 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000011727 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000011728 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011729 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011730 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011731 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011732 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000011733 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011734 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011735 }
11736
John McCall16df1e52010-03-30 21:47:33 +000011737 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000011738
John McCall2d74de92009-12-01 22:10:20 +000011739 // If overload resolution picked a static member, build a
11740 // non-member call based on that function.
11741 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011742 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11743 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000011744 }
11745
John McCall10eae182009-11-30 22:42:35 +000011746 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011747 }
11748
Alp Toker314cc812014-01-25 16:55:45 +000011749 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000011750 ExprValueKind VK = Expr::getValueKindForType(ResultType);
11751 ResultType = ResultType.getNonLValueExprType(Context);
11752
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011753 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011754 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011755 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000011756 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011757
Eli Bendersky291a57e2014-09-25 23:59:08 +000011758 // (CUDA B.1): Check for invalid calls between targets.
11759 if (getLangOpts().CUDA) {
11760 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
11761 if (CheckCUDATarget(Caller, Method)) {
11762 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
11763 << IdentifyCUDATarget(Method) << Method->getIdentifier()
11764 << IdentifyCUDATarget(Caller);
11765 return ExprError();
11766 }
11767 }
11768 }
11769
Anders Carlssonc4859ba2009-10-10 00:06:20 +000011770 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000011771 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000011772 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000011773 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011774
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011775 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000011776 // We only need to do this if there was actually an overload; otherwise
11777 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000011778 if (!Method->isStatic()) {
11779 ExprResult ObjectArg =
11780 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11781 FoundDecl, Method);
11782 if (ObjectArg.isInvalid())
11783 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011784 MemExpr->setBase(ObjectArg.get());
John Wiegley01296292011-04-08 18:41:53 +000011785 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011786
11787 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000011788 const FunctionProtoType *Proto =
11789 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011790 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011791 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000011792 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011793
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011794 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011795
Richard Smith55ce3522012-06-25 20:30:08 +000011796 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000011797 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000011798
Anders Carlsson47061ee2011-05-06 14:25:31 +000011799 if ((isa<CXXConstructorDecl>(CurContext) ||
11800 isa<CXXDestructorDecl>(CurContext)) &&
11801 TheCall->getMethodDecl()->isPure()) {
11802 const CXXMethodDecl *MD = TheCall->getMethodDecl();
11803
Davide Italianoccb37382015-07-14 23:36:10 +000011804 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
11805 MemExpr->performsVirtualDispatch(getLangOpts())) {
11806 Diag(MemExpr->getLocStart(),
Anders Carlsson47061ee2011-05-06 14:25:31 +000011807 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11808 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11809 << MD->getParent()->getDeclName();
11810
11811 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Davide Italianoccb37382015-07-14 23:36:10 +000011812 if (getLangOpts().AppleKext)
11813 Diag(MemExpr->getLocStart(),
11814 diag::note_pure_qualified_call_kext)
11815 << MD->getParent()->getDeclName()
11816 << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000011817 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000011818 }
John McCallb268a282010-08-23 23:25:46 +000011819 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011820}
11821
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011822/// BuildCallToObjectOfClassType - Build a call to an object of class
11823/// type (C++ [over.call.object]), which can end up invoking an
11824/// overloaded function call operator (@c operator()) or performing a
11825/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000011826ExprResult
John Wiegley01296292011-04-08 18:41:53 +000011827Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000011828 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011829 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011830 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000011831 if (checkPlaceholderForOverload(*this, Obj))
11832 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011833 ExprResult Object = Obj;
John McCall4124c492011-10-17 18:40:02 +000011834
11835 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011836 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000011837 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011838
Nico Weberb58e51c2014-11-19 05:21:39 +000011839 assert(Object.get()->getType()->isRecordType() &&
11840 "Requires object type argument");
John Wiegley01296292011-04-08 18:41:53 +000011841 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000011842
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011843 // C++ [over.call.object]p1:
11844 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000011845 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011846 // candidate functions includes at least the function call
11847 // operators of T. The function call operators of T are obtained by
11848 // ordinary lookup of the name operator() in the context of
11849 // (E).operator().
Richard Smith100b24a2014-04-17 01:52:14 +000011850 OverloadCandidateSet CandidateSet(LParenLoc,
11851 OverloadCandidateSet::CSK_Operator);
Douglas Gregor91f84212008-12-11 16:49:14 +000011852 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011853
John Wiegley01296292011-04-08 18:41:53 +000011854 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011855 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011856 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011857
John McCall27b18f82009-11-17 02:14:36 +000011858 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11859 LookupQualifiedName(R, Record->getDecl());
11860 R.suppressDiagnostics();
11861
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011862 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000011863 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000011864 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011865 Object.get()->Classify(Context),
11866 Args, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000011867 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000011868 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011869
Douglas Gregorab7897a2008-11-19 22:57:39 +000011870 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011871 // In addition, for each (non-explicit in C++0x) conversion function
11872 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000011873 //
11874 // operator conversion-type-id () cv-qualifier;
11875 //
11876 // where cv-qualifier is the same cv-qualification as, or a
11877 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000011878 // denotes the type "pointer to function of (P1,...,Pn) returning
11879 // R", or the type "reference to pointer to function of
11880 // (P1,...,Pn) returning R", or the type "reference to function
11881 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000011882 // is also considered as a candidate function. Similarly,
11883 // surrogate call functions are added to the set of candidate
11884 // functions for each conversion function declared in an
11885 // accessible base class provided the function is not hidden
11886 // within T by another intervening declaration.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +000011887 const auto &Conversions =
11888 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
11889 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000011890 NamedDecl *D = *I;
11891 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11892 if (isa<UsingShadowDecl>(D))
11893 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011894
Douglas Gregor74ba25c2009-10-21 06:18:39 +000011895 // Skip over templated conversion functions; they aren't
11896 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000011897 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000011898 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000011899
John McCall6e9f8f62009-12-03 04:06:58 +000011900 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011901 if (!Conv->isExplicit()) {
11902 // Strip the reference type (if any) and then the pointer type (if
11903 // any) to get down to what might be a function type.
11904 QualType ConvType = Conv->getConversionType().getNonReferenceType();
11905 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11906 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000011907
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011908 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11909 {
11910 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011911 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011912 }
11913 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000011914 }
Mike Stump11289f42009-09-09 15:08:12 +000011915
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011916 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11917
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011918 // Perform overload resolution.
11919 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000011920 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000011921 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011922 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000011923 // Overload resolution succeeded; we'll build the appropriate call
11924 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011925 break;
11926
11927 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000011928 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011929 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000011930 << Object.get()->getType() << /*call*/ 1
11931 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000011932 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011933 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000011934 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000011935 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011936 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011937 break;
11938
11939 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011940 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011941 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000011942 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011943 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011944 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011945
11946 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011947 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000011948 diag::err_ovl_deleted_object_call)
11949 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000011950 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011951 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000011952 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011953 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000011954 break;
Mike Stump11289f42009-09-09 15:08:12 +000011955 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011956
Douglas Gregorb412e172010-07-25 18:17:45 +000011957 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011958 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011959
John McCall4124c492011-10-17 18:40:02 +000011960 UnbridgedCasts.restore();
11961
Craig Topperc3ec1492014-05-26 06:22:03 +000011962 if (Best->Function == nullptr) {
Douglas Gregorab7897a2008-11-19 22:57:39 +000011963 // Since there is no function declaration, this is one of the
11964 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000011965 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000011966 = cast<CXXConversionDecl>(
11967 Best->Conversions[0].UserDefined.ConversionFunction);
11968
Craig Topperc3ec1492014-05-26 06:22:03 +000011969 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
11970 Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011971 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11972 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000011973 assert(Conv == Best->FoundDecl.getDecl() &&
11974 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000011975 // We selected one of the surrogate functions that converts the
11976 // object parameter to a function pointer. Perform the conversion
11977 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011978
Fariborz Jahanian774cf792009-09-28 18:35:46 +000011979 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000011980 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011981 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11982 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000011983 if (Call.isInvalid())
11984 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000011985 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011986 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
11987 CK_UserDefinedConversion, Call.get(),
11988 nullptr, VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011989
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011990 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000011991 }
11992
Craig Topperc3ec1492014-05-26 06:22:03 +000011993 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000011994
Douglas Gregorab7897a2008-11-19 22:57:39 +000011995 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11996 // that calls this method, using Object for the implicit object
11997 // parameter and passing along the remaining arguments.
11998 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000011999
12000 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000012001 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000012002 return ExprError();
12003
Chandler Carruth8e543b32010-12-12 08:17:55 +000012004 const FunctionProtoType *Proto =
12005 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012006
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012007 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000012008
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012009 DeclarationNameInfo OpLocInfo(
12010 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
12011 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000012012 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012013 HadMultipleCandidates,
12014 OpLocInfo.getLoc(),
12015 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012016 if (NewFn.isInvalid())
12017 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012018
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012019 // Build the full argument list for the method call (the implicit object
12020 // parameter is placed at the beginning of the list).
Ahmed Charlesaf94d562014-03-09 11:34:25 +000012021 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012022 MethodArgs[0] = Object.get();
12023 std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
12024
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012025 // Once we've built TheCall, all of the expressions are properly
12026 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000012027 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012028 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12029 ResultTy = ResultTy.getNonLValueExprType(Context);
12030
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012031 CXXOperatorCallExpr *TheCall = new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012032 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012033 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
12034 ResultTy, VK, RParenLoc, false);
12035 MethodArgs.reset();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012036
Alp Toker314cc812014-01-25 16:55:45 +000012037 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000012038 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012039
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012040 // We may have default arguments. If so, we need to allocate more
12041 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012042 if (Args.size() < NumParams)
12043 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012044
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012045 bool IsError = false;
12046
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012047 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000012048 ExprResult ObjRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000012049 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012050 Best->FoundDecl, Method);
12051 if (ObjRes.isInvalid())
12052 IsError = true;
12053 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012054 Object = ObjRes;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012055 TheCall->setArg(0, Object.get());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012056
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012057 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012058 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012059 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012060 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012061 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000012062
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012063 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012064
John McCalldadc5752010-08-24 06:29:42 +000012065 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012066 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012067 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012068 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000012069 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012070
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012071 IsError |= InputInit.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012072 Arg = InputInit.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012073 } else {
John McCalldadc5752010-08-24 06:29:42 +000012074 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000012075 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12076 if (DefArg.isInvalid()) {
12077 IsError = true;
12078 break;
12079 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012080
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012081 Arg = DefArg.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012082 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012083
12084 TheCall->setArg(i + 1, Arg);
12085 }
12086
12087 // If this is a variadic call, handle args passed through "...".
12088 if (Proto->isVariadic()) {
12089 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012090 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012091 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12092 nullptr);
John Wiegley01296292011-04-08 18:41:53 +000012093 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012094 TheCall->setArg(i + 1, Arg.get());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012095 }
12096 }
12097
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012098 if (IsError) return true;
12099
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012100 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012101
Richard Smith55ce3522012-06-25 20:30:08 +000012102 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000012103 return true;
12104
John McCalle172be52010-08-24 06:09:16 +000012105 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012106}
12107
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012108/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000012109/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012110/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000012111ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012112Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12113 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000012114 assert(Base->getType()->isRecordType() &&
12115 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000012116
John McCall4124c492011-10-17 18:40:02 +000012117 if (checkPlaceholderForOverload(*this, Base))
12118 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012119
John McCallbc077cf2010-02-08 23:07:23 +000012120 SourceLocation Loc = Base->getExprLoc();
12121
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012122 // C++ [over.ref]p1:
12123 //
12124 // [...] An expression x->m is interpreted as (x.operator->())->m
12125 // for a class object x of type T if T::operator->() exists and if
12126 // the operator is selected as the best match function by the
12127 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000012128 DeclarationName OpName =
12129 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Richard Smith100b24a2014-04-17 01:52:14 +000012130 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000012131 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000012132
John McCallbc077cf2010-02-08 23:07:23 +000012133 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012134 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000012135 return ExprError();
12136
John McCall27b18f82009-11-17 02:14:36 +000012137 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12138 LookupQualifiedName(R, BaseRecord->getDecl());
12139 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000012140
12141 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000012142 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000012143 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000012144 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000012145 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012146
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012147 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12148
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012149 // Perform overload resolution.
12150 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012151 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012152 case OR_Success:
12153 // Overload resolution succeeded; we'll build the call below.
12154 break;
12155
12156 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012157 if (CandidateSet.empty()) {
12158 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012159 if (NoArrowOperatorFound) {
12160 // Report this specific error to the caller instead of emitting a
12161 // diagnostic, as requested.
12162 *NoArrowOperatorFound = true;
12163 return ExprError();
12164 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012165 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12166 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012167 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012168 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012169 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012170 }
12171 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012172 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000012173 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012174 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012175 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012176
12177 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012178 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12179 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012180 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012181 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012182
12183 case OR_Deleted:
12184 Diag(OpLoc, diag::err_ovl_deleted_oper)
12185 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012186 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012187 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012188 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012189 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012190 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012191 }
12192
Craig Topperc3ec1492014-05-26 06:22:03 +000012193 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCalla0296f72010-03-19 07:35:19 +000012194
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012195 // Convert the object parameter.
12196 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000012197 ExprResult BaseResult =
Craig Topperc3ec1492014-05-26 06:22:03 +000012198 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012199 Best->FoundDecl, Method);
12200 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000012201 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012202 Base = BaseResult.get();
Douglas Gregor9ecea262008-11-21 03:04:22 +000012203
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012204 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000012205 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012206 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012207 if (FnExpr.isInvalid())
12208 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012209
Alp Toker314cc812014-01-25 16:55:45 +000012210 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012211 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12212 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000012213 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012214 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012215 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012216
Alp Toker314cc812014-01-25 16:55:45 +000012217 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012218 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000012219
12220 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012221}
12222
Richard Smithbcc22fc2012-03-09 08:00:36 +000012223/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12224/// a literal operator described by the provided lookup results.
12225ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12226 DeclarationNameInfo &SuffixInfo,
12227 ArrayRef<Expr*> Args,
12228 SourceLocation LitEndLoc,
12229 TemplateArgumentListInfo *TemplateArgs) {
12230 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000012231
Richard Smith100b24a2014-04-17 01:52:14 +000012232 OverloadCandidateSet CandidateSet(UDSuffixLoc,
12233 OverloadCandidateSet::CSK_Normal);
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000012234 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12235 /*SuppressUserConversions=*/true);
Richard Smithc67fdd42012-03-07 08:35:16 +000012236
Richard Smithbcc22fc2012-03-09 08:00:36 +000012237 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12238
Richard Smithbcc22fc2012-03-09 08:00:36 +000012239 // Perform overload resolution. This will usually be trivial, but might need
12240 // to perform substitutions for a literal operator template.
12241 OverloadCandidateSet::iterator Best;
12242 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12243 case OR_Success:
12244 case OR_Deleted:
12245 break;
12246
12247 case OR_No_Viable_Function:
12248 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12249 << R.getLookupName();
12250 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12251 return ExprError();
12252
12253 case OR_Ambiguous:
12254 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12255 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12256 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000012257 }
12258
Richard Smithbcc22fc2012-03-09 08:00:36 +000012259 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000012260 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12261 HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000012262 SuffixInfo.getLoc(),
12263 SuffixInfo.getInfo());
12264 if (Fn.isInvalid())
12265 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000012266
12267 // Check the argument types. This should almost always be a no-op, except
12268 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000012269 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000012270 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000012271 ExprResult InputInit = PerformCopyInitialization(
12272 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12273 SourceLocation(), Args[ArgIdx]);
12274 if (InputInit.isInvalid())
12275 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012276 ConvArgs[ArgIdx] = InputInit.get();
Richard Smithc67fdd42012-03-07 08:35:16 +000012277 }
12278
Alp Toker314cc812014-01-25 16:55:45 +000012279 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000012280 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12281 ResultTy = ResultTy.getNonLValueExprType(Context);
12282
Richard Smithc67fdd42012-03-07 08:35:16 +000012283 UserDefinedLiteral *UDL =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012284 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000012285 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000012286 ResultTy, VK, LitEndLoc, UDSuffixLoc);
12287
Alp Toker314cc812014-01-25 16:55:45 +000012288 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000012289 return ExprError();
12290
Craig Topperc3ec1492014-05-26 06:22:03 +000012291 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smithc67fdd42012-03-07 08:35:16 +000012292 return ExprError();
12293
12294 return MaybeBindToTemporary(UDL);
12295}
12296
Sam Panzer0f384432012-08-21 00:52:01 +000012297/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12298/// given LookupResult is non-empty, it is assumed to describe a member which
12299/// will be invoked. Otherwise, the function will be found via argument
12300/// dependent lookup.
12301/// CallExpr is set to a valid expression and FRS_Success returned on success,
12302/// otherwise CallExpr is set to ExprError() and some non-success value
12303/// is returned.
12304Sema::ForRangeStatus
12305Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
12306 SourceLocation RangeLoc, VarDecl *Decl,
12307 BeginEndFunction BEF,
12308 const DeclarationNameInfo &NameInfo,
12309 LookupResult &MemberLookup,
12310 OverloadCandidateSet *CandidateSet,
12311 Expr *Range, ExprResult *CallExpr) {
12312 CandidateSet->clear();
12313 if (!MemberLookup.empty()) {
12314 ExprResult MemberRef =
12315 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12316 /*IsPtr=*/false, CXXScopeSpec(),
12317 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012318 /*FirstQualifierInScope=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012319 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +000012320 /*TemplateArgs=*/nullptr, S);
Sam Panzer0f384432012-08-21 00:52:01 +000012321 if (MemberRef.isInvalid()) {
12322 *CallExpr = ExprError();
12323 Diag(Range->getLocStart(), diag::note_in_for_range)
12324 << RangeLoc << BEF << Range->getType();
12325 return FRS_DiagnosticIssued;
12326 }
Craig Topperc3ec1492014-05-26 06:22:03 +000012327 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000012328 if (CallExpr->isInvalid()) {
12329 *CallExpr = ExprError();
12330 Diag(Range->getLocStart(), diag::note_in_for_range)
12331 << RangeLoc << BEF << Range->getType();
12332 return FRS_DiagnosticIssued;
12333 }
12334 } else {
12335 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000012336 UnresolvedLookupExpr *Fn =
Craig Topperc3ec1492014-05-26 06:22:03 +000012337 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012338 NestedNameSpecifierLoc(), NameInfo,
12339 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000012340 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000012341
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012342 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000012343 CandidateSet, CallExpr);
12344 if (CandidateSet->empty() || CandidateSetError) {
12345 *CallExpr = ExprError();
12346 return FRS_NoViableFunction;
12347 }
12348 OverloadCandidateSet::iterator Best;
12349 OverloadingResult OverloadResult =
12350 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12351
12352 if (OverloadResult == OR_No_Viable_Function) {
12353 *CallExpr = ExprError();
12354 return FRS_NoViableFunction;
12355 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012356 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Craig Topperc3ec1492014-05-26 06:22:03 +000012357 Loc, nullptr, CandidateSet, &Best,
Sam Panzer0f384432012-08-21 00:52:01 +000012358 OverloadResult,
12359 /*AllowTypoCorrection=*/false);
12360 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12361 *CallExpr = ExprError();
12362 Diag(Range->getLocStart(), diag::note_in_for_range)
12363 << RangeLoc << BEF << Range->getType();
12364 return FRS_DiagnosticIssued;
12365 }
12366 }
12367 return FRS_Success;
12368}
12369
12370
Douglas Gregorcd695e52008-11-10 20:40:00 +000012371/// FixOverloadedFunctionReference - E is an expression that refers to
12372/// a C++ overloaded function (possibly with some parentheses and
12373/// perhaps a '&' around it). We have resolved the overloaded function
12374/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000012375/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000012376Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000012377 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000012378 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012379 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12380 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012381 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012382 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012383
Douglas Gregor51c538b2009-11-20 19:42:02 +000012384 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012385 }
12386
Douglas Gregor51c538b2009-11-20 19:42:02 +000012387 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012388 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12389 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012390 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000012391 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000012392 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000012393 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000012394 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012395 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012396
12397 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000012398 ICE->getCastKind(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012399 SubExpr, nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000012400 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012401 }
12402
Douglas Gregor51c538b2009-11-20 19:42:02 +000012403 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000012404 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000012405 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012406 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12407 if (Method->isStatic()) {
12408 // Do nothing: static member functions aren't any different
12409 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000012410 } else {
Alp Toker028ed912013-12-06 17:56:43 +000012411 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000012412 // UnresolvedLookupExpr holding an overloaded member function
12413 // or template.
John McCall16df1e52010-03-30 21:47:33 +000012414 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12415 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000012416 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012417 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012418
John McCalld14a8642009-11-21 08:51:07 +000012419 assert(isa<DeclRefExpr>(SubExpr)
12420 && "fixed to something other than a decl ref");
12421 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12422 && "fixed to a member ref with no nested name qualifier");
12423
12424 // We have taken the address of a pointer to member
12425 // function. Perform the computation here so that we get the
12426 // appropriate pointer to member type.
12427 QualType ClassType
12428 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12429 QualType MemPtrType
12430 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12431
John McCall7decc9e2010-11-18 06:31:45 +000012432 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12433 VK_RValue, OK_Ordinary,
12434 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012435 }
12436 }
John McCall16df1e52010-03-30 21:47:33 +000012437 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12438 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012439 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012440 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012441
John McCalle3027922010-08-25 11:45:40 +000012442 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012443 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000012444 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012445 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012446 }
John McCalld14a8642009-11-21 08:51:07 +000012447
12448 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000012449 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012450 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCalle66edc12009-11-24 19:00:30 +000012451 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000012452 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12453 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000012454 }
12455
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012456 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12457 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012458 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012459 Fn,
John McCall113bee02012-03-10 09:33:50 +000012460 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012461 ULE->getNameLoc(),
12462 Fn->getType(),
12463 VK_LValue,
12464 Found.getDecl(),
12465 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012466 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012467 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12468 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000012469 }
12470
John McCall10eae182009-11-30 22:42:35 +000012471 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000012472 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012473 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012474 if (MemExpr->hasExplicitTemplateArgs()) {
12475 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12476 TemplateArgs = &TemplateArgsBuffer;
12477 }
John McCall6b51f282009-11-23 01:53:49 +000012478
John McCall2d74de92009-12-01 22:10:20 +000012479 Expr *Base;
12480
John McCall7decc9e2010-11-18 06:31:45 +000012481 // If we're filling in a static method where we used to have an
12482 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000012483 if (MemExpr->isImplicitAccess()) {
12484 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012485 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12486 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012487 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012488 Fn,
John McCall113bee02012-03-10 09:33:50 +000012489 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012490 MemExpr->getMemberLoc(),
12491 Fn->getType(),
12492 VK_LValue,
12493 Found.getDecl(),
12494 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012495 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012496 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
12497 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000012498 } else {
12499 SourceLocation Loc = MemExpr->getMemberLoc();
12500 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000012501 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000012502 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000012503 Base = new (Context) CXXThisExpr(Loc,
12504 MemExpr->getBaseType(),
12505 /*isImplicit=*/true);
12506 }
John McCall2d74de92009-12-01 22:10:20 +000012507 } else
John McCallc3007a22010-10-26 07:05:15 +000012508 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000012509
John McCall4adb38c2011-04-27 00:36:17 +000012510 ExprValueKind valueKind;
12511 QualType type;
12512 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12513 valueKind = VK_LValue;
12514 type = Fn->getType();
12515 } else {
12516 valueKind = VK_RValue;
Yunzhong Gaoeba323a2015-05-01 02:04:32 +000012517 type = Context.BoundMemberTy;
12518 }
12519
12520 MemberExpr *ME = MemberExpr::Create(
12521 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
12522 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
12523 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
12524 OK_Ordinary);
12525 ME->setHadMultipleCandidates(true);
12526 MarkMemberReferenced(ME);
12527 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012528 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012529
John McCallc3007a22010-10-26 07:05:15 +000012530 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000012531}
12532
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012533ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000012534 DeclAccessPair Found,
12535 FunctionDecl *Fn) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012536 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor3e1e5272009-12-09 23:02:17 +000012537}