blob: 0ba559830151ea138731ed709c965bbd1bb43503 [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
Richard Smithf091e122015-09-15 01:28:55 +0000899 // A using-declaration does not conflict with another declaration
900 // if one of them is hidden.
901 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
902 continue;
903
John McCalle9cccd82010-06-16 08:42:20 +0000904 // If either declaration was introduced by a using declaration,
905 // we'll need to use slightly different rules for matching.
906 // Essentially, these rules are the normal rules, except that
907 // function templates hide function templates with different
908 // return types or template parameter lists.
909 bool UseMemberUsingDeclRules =
John McCallc70fca62013-04-03 21:19:47 +0000910 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
911 !New->getFriendObjectKind();
John McCalle9cccd82010-06-16 08:42:20 +0000912
Alp Tokera2794f92014-01-22 07:29:52 +0000913 if (FunctionDecl *OldF = OldD->getAsFunction()) {
John McCalle9cccd82010-06-16 08:42:20 +0000914 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
915 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
916 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
917 continue;
918 }
919
Alp Tokera2794f92014-01-22 07:29:52 +0000920 if (!isa<FunctionTemplateDecl>(OldD) &&
921 !shouldLinkPossiblyHiddenDecl(*I, New))
Rafael Espindola5bddd6a2013-04-15 12:49:13 +0000922 continue;
923
John McCalldaa3d6b2009-12-09 03:35:25 +0000924 Match = *I;
925 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000926 }
John McCalla8987a2942010-11-10 03:01:53 +0000927 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000928 // We can overload with these, which can show up when doing
929 // redeclaration checks for UsingDecls.
930 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000931 } else if (isa<TagDecl>(OldD)) {
932 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000933 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
934 // Optimistically assume that an unresolved using decl will
935 // overload; if it doesn't, we'll have to diagnose during
936 // template instantiation.
937 } else {
John McCall1f82f242009-11-18 22:49:29 +0000938 // (C++ 13p1):
939 // Only function declarations can be overloaded; object and type
940 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000941 Match = *I;
942 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000943 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000944 }
John McCall1f82f242009-11-18 22:49:29 +0000945
John McCalldaa3d6b2009-12-09 03:35:25 +0000946 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000947}
948
Richard Smithac974a32013-06-30 09:48:50 +0000949bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
950 bool UseUsingDeclRules) {
951 // C++ [basic.start.main]p2: This function shall not be overloaded.
952 if (New->isMain())
Rafael Espindola576127d2012-12-28 14:21:58 +0000953 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +0000954
David Majnemerc729b0b2013-09-16 22:44:20 +0000955 // MSVCRT user defined entry points cannot be overloaded.
956 if (New->isMSVCRTEntryPoint())
957 return false;
958
John McCall1f82f242009-11-18 22:49:29 +0000959 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
960 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
961
962 // C++ [temp.fct]p2:
963 // A function template can be overloaded with other function templates
964 // and with normal (non-template) functions.
Craig Topperc3ec1492014-05-26 06:22:03 +0000965 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
John McCall1f82f242009-11-18 22:49:29 +0000966 return true;
967
968 // Is the function New an overload of the function Old?
Richard Smithac974a32013-06-30 09:48:50 +0000969 QualType OldQType = Context.getCanonicalType(Old->getType());
970 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall1f82f242009-11-18 22:49:29 +0000971
972 // Compare the signatures (C++ 1.3.10) of the two functions to
973 // determine whether they are overloads. If we find any mismatch
974 // in the signature, they are overloads.
975
976 // If either of these functions is a K&R-style function (no
977 // prototype), then we consider them to have matching signatures.
978 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
979 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
980 return false;
981
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000982 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
983 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000984
985 // The signature of a function includes the types of its
986 // parameters (C++ 1.3.10), which includes the presence or absence
987 // of the ellipsis; see C++ DR 357).
988 if (OldQType != NewQType &&
Alp Toker9cacbab2014-01-20 20:26:09 +0000989 (OldType->getNumParams() != NewType->getNumParams() ||
John McCall1f82f242009-11-18 22:49:29 +0000990 OldType->isVariadic() != NewType->isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +0000991 !FunctionParamTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000992 return true;
993
994 // C++ [temp.over.link]p4:
995 // The signature of a function template consists of its function
996 // signature, its return type and its template parameter list. The names
997 // of the template parameters are significant only for establishing the
998 // relationship between the template parameters and the rest of the
999 // signature.
1000 //
1001 // We check the return type and template parameter lists for function
1002 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +00001003 //
1004 // However, we don't consider either of these when deciding whether
1005 // a member introduced by a shadow declaration is hidden.
1006 if (!UseUsingDeclRules && NewTemplate &&
Richard Smithac974a32013-06-30 09:48:50 +00001007 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1008 OldTemplate->getTemplateParameters(),
1009 false, TPL_TemplateMatch) ||
Alp Toker314cc812014-01-25 16:55:45 +00001010 OldType->getReturnType() != NewType->getReturnType()))
John McCall1f82f242009-11-18 22:49:29 +00001011 return true;
1012
1013 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001014 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001015 //
1016 // As part of this, also check whether one of the member functions
1017 // is static, in which case they are not overloads (C++
1018 // 13.1p2). While not part of the definition of the signature,
1019 // this check is important to determine whether these functions
1020 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001021 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1022 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001023 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001024 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1025 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1026 if (!UseUsingDeclRules &&
1027 (OldMethod->getRefQualifier() == RQ_None ||
1028 NewMethod->getRefQualifier() == RQ_None)) {
1029 // C++0x [over.load]p2:
1030 // - Member function declarations with the same name and the same
1031 // parameter-type-list as well as member function template
1032 // declarations with the same name, the same parameter-type-list, and
1033 // the same template parameter lists cannot be overloaded if any of
1034 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001035 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001036 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001037 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001038 }
1039 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001040 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001041
Richard Smith574f4f62013-01-14 05:37:29 +00001042 // We may not have applied the implicit const for a constexpr member
1043 // function yet (because we haven't yet resolved whether this is a static
1044 // or non-static member function). Add it now, on the assumption that this
1045 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001046 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001047 unsigned NewQuals = NewMethod->getTypeQualifiers();
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001048 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001049 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001050 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001051
1052 // We do not allow overloading based off of '__restrict'.
1053 OldQuals &= ~Qualifiers::Restrict;
1054 NewQuals &= ~Qualifiers::Restrict;
1055 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001056 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001057 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001058
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001059 // enable_if attributes are an order-sensitive part of the signature.
1060 for (specific_attr_iterator<EnableIfAttr>
1061 NewI = New->specific_attr_begin<EnableIfAttr>(),
1062 NewE = New->specific_attr_end<EnableIfAttr>(),
1063 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1064 OldE = Old->specific_attr_end<EnableIfAttr>();
1065 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1066 if (NewI == NewE || OldI == OldE)
1067 return true;
1068 llvm::FoldingSetNodeID NewID, OldID;
1069 NewI->getCond()->Profile(NewID, Context, true);
1070 OldI->getCond()->Profile(OldID, Context, true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00001071 if (NewID != OldID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001072 return true;
1073 }
1074
John McCall1f82f242009-11-18 22:49:29 +00001075 // The signatures match; this is not an overload.
1076 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001077}
1078
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001079/// \brief Checks availability of the function depending on the current
1080/// function context. Inside an unavailable function, unavailability is ignored.
1081///
1082/// \returns true if \arg FD is unavailable and current context is inside
1083/// an available function, false otherwise.
1084bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1085 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1086}
1087
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001088/// \brief Tries a user-defined conversion from From to ToType.
1089///
1090/// Produces an implicit conversion sequence for when a standard conversion
1091/// is not an option. See TryImplicitConversion for more information.
1092static ImplicitConversionSequence
1093TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1094 bool SuppressUserConversions,
1095 bool AllowExplicit,
1096 bool InOverloadResolution,
1097 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001098 bool AllowObjCWritebackConversion,
1099 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001100 ImplicitConversionSequence ICS;
1101
1102 if (SuppressUserConversions) {
1103 // We're not in the case above, so there is no conversion that
1104 // we can perform.
1105 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1106 return ICS;
1107 }
1108
1109 // Attempt user-defined conversion.
Richard Smith100b24a2014-04-17 01:52:14 +00001110 OverloadCandidateSet Conversions(From->getExprLoc(),
1111 OverloadCandidateSet::CSK_Normal);
Richard Smith48372b62015-01-27 03:30:40 +00001112 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1113 Conversions, AllowExplicit,
1114 AllowObjCConversionOnExplicit)) {
1115 case OR_Success:
1116 case OR_Deleted:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001117 ICS.setUserDefined();
Ismail Pazarbasidf1a2802014-01-24 13:16:17 +00001118 ICS.UserDefined.Before.setAsIdentityConversion();
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001119 // C++ [over.ics.user]p4:
1120 // A conversion of an expression of class type to the same class
1121 // type is given Exact Match rank, and a conversion of an
1122 // expression of class type to a base class of that type is
1123 // given Conversion rank, in spite of the fact that a copy
1124 // constructor (i.e., a user-defined conversion function) is
1125 // called for those cases.
1126 if (CXXConstructorDecl *Constructor
1127 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1128 QualType FromCanon
1129 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1130 QualType ToCanon
1131 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1132 if (Constructor->isCopyConstructor() &&
1133 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1134 // Turn this into a "standard" conversion sequence, so that it
1135 // gets ranked with standard conversion sequences.
1136 ICS.setStandard();
1137 ICS.Standard.setAsIdentityConversion();
1138 ICS.Standard.setFromType(From->getType());
1139 ICS.Standard.setAllToTypes(ToType);
1140 ICS.Standard.CopyConstructor = Constructor;
1141 if (ToCanon != FromCanon)
1142 ICS.Standard.Second = ICK_Derived_To_Base;
1143 }
1144 }
Richard Smith48372b62015-01-27 03:30:40 +00001145 break;
1146
1147 case OR_Ambiguous:
Richard Smith1bbaba82015-01-27 23:23:39 +00001148 ICS.setAmbiguous();
1149 ICS.Ambiguous.setFromType(From->getType());
1150 ICS.Ambiguous.setToType(ToType);
1151 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1152 Cand != Conversions.end(); ++Cand)
1153 if (Cand->Viable)
1154 ICS.Ambiguous.addConversion(Cand->Function);
1155 break;
Richard Smith48372b62015-01-27 03:30:40 +00001156
1157 // Fall through.
1158 case OR_No_Viable_Function:
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001159 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Richard Smith48372b62015-01-27 03:30:40 +00001160 break;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001161 }
1162
1163 return ICS;
1164}
1165
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001166/// TryImplicitConversion - Attempt to perform an implicit conversion
1167/// from the given expression (Expr) to the given type (ToType). This
1168/// function returns an implicit conversion sequence that can be used
1169/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001170///
1171/// void f(float f);
1172/// void g(int i) { f(i); }
1173///
1174/// this routine would produce an implicit conversion sequence to
1175/// describe the initialization of f from i, which will be a standard
1176/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1177/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1178//
1179/// Note that this routine only determines how the conversion can be
1180/// performed; it does not actually perform the conversion. As such,
1181/// it will not produce any diagnostics if no conversion is available,
1182/// but will instead return an implicit conversion sequence of kind
1183/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001184///
1185/// If @p SuppressUserConversions, then user-defined conversions are
1186/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001187/// If @p AllowExplicit, then explicit user-defined conversions are
1188/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001189///
1190/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1191/// writeback conversion, which allows __autoreleasing id* parameters to
1192/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001193static ImplicitConversionSequence
1194TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1195 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001196 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001197 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001198 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001199 bool AllowObjCWritebackConversion,
1200 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001201 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001202 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001203 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001204 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001205 return ICS;
1206 }
1207
David Blaikiebbafb8a2012-03-11 07:00:24 +00001208 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001209 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001210 return ICS;
1211 }
1212
Douglas Gregor836a7e82010-08-11 02:15:33 +00001213 // C++ [over.ics.user]p4:
1214 // A conversion of an expression of class type to the same class
1215 // type is given Exact Match rank, and a conversion of an
1216 // expression of class type to a base class of that type is
1217 // given Conversion rank, in spite of the fact that a copy/move
1218 // constructor (i.e., a user-defined conversion function) is
1219 // called for those cases.
1220 QualType FromType = From->getType();
1221 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001222 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1223 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001224 ICS.setStandard();
1225 ICS.Standard.setAsIdentityConversion();
1226 ICS.Standard.setFromType(FromType);
1227 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001228
Douglas Gregor5ab11652010-04-17 22:01:05 +00001229 // We don't actually check at this point whether there is a valid
1230 // copy/move constructor, since overloading just assumes that it
1231 // exists. When we actually perform initialization, we'll find the
1232 // appropriate constructor to copy the returned object, if needed.
Craig Topperc3ec1492014-05-26 06:22:03 +00001233 ICS.Standard.CopyConstructor = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001234
Douglas Gregor5ab11652010-04-17 22:01:05 +00001235 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001236 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001237 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001238
Douglas Gregor836a7e82010-08-11 02:15:33 +00001239 return ICS;
1240 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001241
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001242 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1243 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001244 AllowObjCWritebackConversion,
1245 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001246}
1247
John McCall31168b02011-06-15 23:02:42 +00001248ImplicitConversionSequence
1249Sema::TryImplicitConversion(Expr *From, QualType ToType,
1250 bool SuppressUserConversions,
1251 bool AllowExplicit,
1252 bool InOverloadResolution,
1253 bool CStyle,
1254 bool AllowObjCWritebackConversion) {
Richard Smith17c00b42014-11-12 01:24:00 +00001255 return ::TryImplicitConversion(*this, From, ToType,
1256 SuppressUserConversions, AllowExplicit,
1257 InOverloadResolution, CStyle,
1258 AllowObjCWritebackConversion,
1259 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001260}
1261
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001262/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001263/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001264/// converted expression. Flavor is the kind of conversion we're
1265/// performing, used in the error message. If @p AllowExplicit,
1266/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001267ExprResult
1268Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001269 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001270 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001271 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001272}
1273
John Wiegley01296292011-04-08 18:41:53 +00001274ExprResult
1275Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001276 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001277 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001278 if (checkPlaceholderForOverload(*this, From))
1279 return ExprError();
1280
John McCall31168b02011-06-15 23:02:42 +00001281 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1282 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001283 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001284 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001285 if (getLangOpts().ObjC1)
1286 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1287 ToType, From->getType(), From);
Richard Smith17c00b42014-11-12 01:24:00 +00001288 ICS = ::TryImplicitConversion(*this, From, ToType,
1289 /*SuppressUserConversions=*/false,
1290 AllowExplicit,
1291 /*InOverloadResolution=*/false,
1292 /*CStyle=*/false,
1293 AllowObjCWritebackConversion,
1294 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001295 return PerformImplicitConversion(From, ToType, ICS, Action);
1296}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001297
1298/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001299/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001300bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1301 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001302 if (Context.hasSameUnqualifiedType(FromType, ToType))
1303 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001304
John McCall991eb4b2010-12-21 00:44:39 +00001305 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1306 // where F adds one of the following at most once:
1307 // - a pointer
1308 // - a member pointer
1309 // - a block pointer
1310 CanQualType CanTo = Context.getCanonicalType(ToType);
1311 CanQualType CanFrom = Context.getCanonicalType(FromType);
1312 Type::TypeClass TyClass = CanTo->getTypeClass();
1313 if (TyClass != CanFrom->getTypeClass()) return false;
1314 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1315 if (TyClass == Type::Pointer) {
1316 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1317 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1318 } else if (TyClass == Type::BlockPointer) {
1319 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1320 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1321 } else if (TyClass == Type::MemberPointer) {
1322 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1323 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1324 } else {
1325 return false;
1326 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001327
John McCall991eb4b2010-12-21 00:44:39 +00001328 TyClass = CanTo->getTypeClass();
1329 if (TyClass != CanFrom->getTypeClass()) return false;
1330 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1331 return false;
1332 }
1333
1334 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1335 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1336 if (!EInfo.getNoReturn()) return false;
1337
1338 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1339 assert(QualType(FromFn, 0).isCanonical());
1340 if (QualType(FromFn, 0) != CanTo) return false;
1341
1342 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001343 return true;
1344}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001345
Douglas Gregor46188682010-05-18 22:42:18 +00001346/// \brief Determine whether the conversion from FromType to ToType is a valid
1347/// vector conversion.
1348///
1349/// \param ICK Will be set to the vector conversion kind, if this is a vector
1350/// conversion.
John McCall9b595db2014-02-04 23:58:19 +00001351static bool IsVectorConversion(Sema &S, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001352 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001353 // We need at least one of these types to be a vector type to have a vector
1354 // conversion.
1355 if (!ToType->isVectorType() && !FromType->isVectorType())
1356 return false;
1357
1358 // Identical types require no conversions.
John McCall9b595db2014-02-04 23:58:19 +00001359 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor46188682010-05-18 22:42:18 +00001360 return false;
1361
1362 // There are no conversions between extended vector types, only identity.
1363 if (ToType->isExtVectorType()) {
1364 // There are no conversions between extended vector types other than the
1365 // identity conversion.
1366 if (FromType->isExtVectorType())
1367 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001368
Douglas Gregor46188682010-05-18 22:42:18 +00001369 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001370 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001371 ICK = ICK_Vector_Splat;
1372 return true;
1373 }
1374 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001375
1376 // We can perform the conversion between vector types in the following cases:
1377 // 1)vector types are equivalent AltiVec and GCC vector types
1378 // 2)lax vector conversions are permitted and the vector types are of the
1379 // same size
1380 if (ToType->isVectorType() && FromType->isVectorType()) {
John McCall9b595db2014-02-04 23:58:19 +00001381 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1382 S.isLaxVectorConversion(FromType, ToType)) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001383 ICK = ICK_Vector_Conversion;
1384 return true;
1385 }
Douglas Gregor46188682010-05-18 22:42:18 +00001386 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001387
Douglas Gregor46188682010-05-18 22:42:18 +00001388 return false;
1389}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001390
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001391static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1392 bool InOverloadResolution,
1393 StandardConversionSequence &SCS,
1394 bool CStyle);
Douglas Gregorc79862f2012-04-12 17:51:55 +00001395
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001396/// IsStandardConversion - Determines whether there is a standard
1397/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1398/// expression From to the type ToType. Standard conversion sequences
1399/// only consider non-class types; for conversions that involve class
1400/// types, use TryImplicitConversion. If a conversion exists, SCS will
1401/// contain the standard conversion sequence required to perform this
1402/// conversion and this routine will return true. Otherwise, this
1403/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001404static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1405 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001406 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001407 bool CStyle,
1408 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001409 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001410
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001411 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001412 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001413 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001414 SCS.setFromType(FromType);
Craig Topperc3ec1492014-05-26 06:22:03 +00001415 SCS.CopyConstructor = nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001416
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001417 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001418 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001419 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001420 if (S.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001421 return false;
1422
Mike Stump11289f42009-09-09 15:08:12 +00001423 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001424 }
1425
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001426 // The first conversion can be an lvalue-to-rvalue conversion,
1427 // array-to-pointer conversion, or function-to-pointer conversion
1428 // (C++ 4p1).
1429
John McCall5c32be02010-08-24 20:38:10 +00001430 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001431 DeclAccessPair AccessPair;
1432 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001433 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001434 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001435 // We were able to resolve the address of the overloaded function,
1436 // so we can convert to the type of that function.
1437 FromType = Fn->getType();
Ehsan Akhgaric3ad3ba2014-07-22 20:20:14 +00001438 SCS.setFromType(FromType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00001439
1440 // we can sometimes resolve &foo<int> regardless of ToType, so check
1441 // if the type matches (identity) or we are converting to bool
1442 if (!S.Context.hasSameUnqualifiedType(
1443 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1444 QualType resultTy;
1445 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001446 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001447 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1448 // otherwise, only a boolean conversion is standard
1449 if (!ToType->isBooleanType())
1450 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001451 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001452
Chandler Carruthffce2452011-03-29 08:08:18 +00001453 // Check if the "from" expression is taking the address of an overloaded
1454 // function and recompute the FromType accordingly. Take advantage of the
1455 // fact that non-static member functions *must* have such an address-of
1456 // expression.
1457 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1458 if (Method && !Method->isStatic()) {
1459 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1460 "Non-unary operator on non-static member address");
1461 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1462 == UO_AddrOf &&
1463 "Non-address-of operator on non-static member address");
1464 const Type *ClassType
1465 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1466 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001467 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1468 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1469 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001470 "Non-address-of operator for overloaded function expression");
1471 FromType = S.Context.getPointerType(FromType);
1472 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001473
Douglas Gregor980fb162010-04-29 18:24:40 +00001474 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001475 assert(S.Context.hasSameType(
1476 FromType,
1477 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001478 } else {
1479 return false;
1480 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001481 }
John McCall154a2fd2011-08-30 00:57:29 +00001482 // Lvalue-to-rvalue conversion (C++11 4.1):
1483 // A glvalue (3.10) of a non-function, non-array type T can
1484 // be converted to a prvalue.
1485 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001486 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001487 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001488 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001489 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001490
Douglas Gregorc79862f2012-04-12 17:51:55 +00001491 // C11 6.3.2.1p2:
1492 // ... if the lvalue has atomic type, the value has the non-atomic version
1493 // of the type of the lvalue ...
1494 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1495 FromType = Atomic->getValueType();
1496
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001497 // If T is a non-class type, the type of the rvalue is the
1498 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001499 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1500 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001501 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001502 } else if (FromType->isArrayType()) {
1503 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001504 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001505
1506 // An lvalue or rvalue of type "array of N T" or "array of unknown
1507 // bound of T" can be converted to an rvalue of type "pointer to
1508 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001509 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001510
John McCall5c32be02010-08-24 20:38:10 +00001511 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001512 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001513 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001514
1515 // For the purpose of ranking in overload resolution
1516 // (13.3.3.1.1), this conversion is considered an
1517 // array-to-pointer conversion followed by a qualification
1518 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001519 SCS.Second = ICK_Identity;
1520 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001521 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001522 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001523 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001524 }
John McCall086a4642010-11-24 05:12:34 +00001525 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001526 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001527 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001528
1529 // An lvalue of function type T can be converted to an rvalue of
1530 // type "pointer to T." The result is a pointer to the
1531 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001532 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001533 } else {
1534 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001535 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001536 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001537 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001538
1539 // The second conversion can be an integral promotion, floating
1540 // point promotion, integral conversion, floating point conversion,
1541 // floating-integral conversion, pointer conversion,
1542 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001543 // For overloading in C, this can also be a "compatible-type"
1544 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001545 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001546 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001547 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001548 // The unqualified versions of the types are the same: there's no
1549 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001550 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001551 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001552 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001553 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001554 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001555 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001556 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001557 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001558 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001559 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001560 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001561 SCS.Second = ICK_Complex_Promotion;
1562 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001563 } else if (ToType->isBooleanType() &&
1564 (FromType->isArithmeticType() ||
1565 FromType->isAnyPointerType() ||
1566 FromType->isBlockPointerType() ||
1567 FromType->isMemberPointerType() ||
1568 FromType->isNullPtrType())) {
1569 // Boolean conversions (C++ 4.12).
1570 SCS.Second = ICK_Boolean_Conversion;
1571 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001572 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001573 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001574 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001575 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001576 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001577 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001578 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001579 SCS.Second = ICK_Complex_Conversion;
1580 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001581 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1582 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001583 // Complex-real conversions (C99 6.3.1.7)
1584 SCS.Second = ICK_Complex_Real;
1585 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001586 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001587 // Floating point conversions (C++ 4.8).
1588 SCS.Second = ICK_Floating_Conversion;
1589 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001590 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001591 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001592 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001593 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001594 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001595 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001596 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001597 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001598 SCS.Second = ICK_Block_Pointer_Conversion;
1599 } else if (AllowObjCWritebackConversion &&
1600 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1601 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001602 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1603 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001604 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001605 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001606 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001607 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001608 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001609 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001610 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001611 SCS.Second = ICK_Pointer_Member;
John McCall9b595db2014-02-04 23:58:19 +00001612 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001613 SCS.Second = SecondICK;
1614 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001615 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001616 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001617 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001618 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001619 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001620 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001621 // Treat a conversion that strips "noreturn" as an identity conversion.
1622 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001623 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1624 InOverloadResolution,
1625 SCS, CStyle)) {
1626 SCS.Second = ICK_TransparentUnionConversion;
1627 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001628 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1629 CStyle)) {
1630 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001631 // appropriately.
1632 return true;
Guy Benyei259f9f42013-02-07 16:05:33 +00001633 } else if (ToType->isEventT() &&
1634 From->isIntegerConstantExpr(S.getASTContext()) &&
1635 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1636 SCS.Second = ICK_Zero_Event_Conversion;
1637 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001638 } else {
1639 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001640 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001641 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001642 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001643
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001644 QualType CanonFrom;
1645 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001646 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001647 bool ObjCLifetimeConversion;
1648 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1649 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001650 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001651 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001652 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001653 CanonFrom = S.Context.getCanonicalType(FromType);
1654 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001655 } else {
1656 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001657 SCS.Third = ICK_Identity;
1658
Mike Stump11289f42009-09-09 15:08:12 +00001659 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001660 // [...] Any difference in top-level cv-qualification is
1661 // subsumed by the initialization itself and does not constitute
1662 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001663 CanonFrom = S.Context.getCanonicalType(FromType);
1664 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001665 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001666 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault7d36c012013-02-26 21:15:54 +00001667 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001668 FromType = ToType;
1669 CanonFrom = CanonTo;
1670 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001671 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001672 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001673
1674 // If we have not converted the argument type to the parameter type,
1675 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001676 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001677 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001678
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001679 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001680}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001681
1682static bool
1683IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1684 QualType &ToType,
1685 bool InOverloadResolution,
1686 StandardConversionSequence &SCS,
1687 bool CStyle) {
1688
1689 const RecordType *UT = ToType->getAsUnionType();
1690 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1691 return false;
1692 // The field to initialize within the transparent union.
1693 RecordDecl *UD = UT->getDecl();
1694 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001695 for (const auto *it : UD->fields()) {
John McCall31168b02011-06-15 23:02:42 +00001696 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1697 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001698 ToType = it->getType();
1699 return true;
1700 }
1701 }
1702 return false;
1703}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001704
1705/// IsIntegralPromotion - Determines whether the conversion from the
1706/// expression From (whose potentially-adjusted type is FromType) to
1707/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1708/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001709bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001710 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001711 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001712 if (!To) {
1713 return false;
1714 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001715
1716 // An rvalue of type char, signed char, unsigned char, short int, or
1717 // unsigned short int can be converted to an rvalue of type int if
1718 // int can represent all the values of the source type; otherwise,
1719 // the source rvalue can be converted to an rvalue of type unsigned
1720 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001721 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1722 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001723 if (// We can promote any signed, promotable integer type to an int
1724 (FromType->isSignedIntegerType() ||
1725 // We can promote any unsigned integer type whose size is
1726 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001727 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001728 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001729 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001730 }
1731
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001732 return To->getKind() == BuiltinType::UInt;
1733 }
1734
Richard Smithb9c5a602012-09-13 21:18:54 +00001735 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001736 // A prvalue of an unscoped enumeration type whose underlying type is not
1737 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1738 // following types that can represent all the values of the enumeration
1739 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1740 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001741 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001742 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001743 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001744 // with lowest integer conversion rank (4.13) greater than the rank of long
1745 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001746 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001747 // C++11 [conv.prom]p4:
1748 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1749 // can be converted to a prvalue of its underlying type. Moreover, if
1750 // integral promotion can be applied to its underlying type, a prvalue of an
1751 // unscoped enumeration type whose underlying type is fixed can also be
1752 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001753 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1754 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1755 // provided for a scoped enumeration.
1756 if (FromEnumType->getDecl()->isScoped())
1757 return false;
1758
Richard Smithb9c5a602012-09-13 21:18:54 +00001759 // We can perform an integral promotion to the underlying type of the enum,
Richard Smithac8c1752015-03-28 00:31:40 +00001760 // even if that's not the promoted type. Note that the check for promoting
1761 // the underlying type is based on the type alone, and does not consider
1762 // the bitfield-ness of the actual source expression.
Richard Smithb9c5a602012-09-13 21:18:54 +00001763 if (FromEnumType->getDecl()->isFixed()) {
1764 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1765 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
Richard Smithac8c1752015-03-28 00:31:40 +00001766 IsIntegralPromotion(nullptr, Underlying, ToType);
Richard Smithb9c5a602012-09-13 21:18:54 +00001767 }
1768
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001769 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001770 if (ToType->isIntegerType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001771 !RequireCompleteType(From->getLocStart(), FromType, 0))
Richard Smith88f4bba2015-03-26 00:16:07 +00001772 return Context.hasSameUnqualifiedType(
1773 ToType, FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001774 }
John McCall56774992009-12-09 09:09:27 +00001775
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001776 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001777 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1778 // to an rvalue a prvalue of the first of the following types that can
1779 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001780 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001781 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001782 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001783 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001784 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001785 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001786 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001787 // Determine whether the type we're converting from is signed or
1788 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001789 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001790 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001791
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001792 // The types we'll try to promote to, in the appropriate
1793 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001794 QualType PromoteTypes[6] = {
1795 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001796 Context.LongTy, Context.UnsignedLongTy ,
1797 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001798 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001799 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001800 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1801 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001802 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001803 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1804 // We found the type that we can promote to. If this is the
1805 // type we wanted, we have a promotion. Otherwise, no
1806 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001807 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001808 }
1809 }
1810 }
1811
1812 // An rvalue for an integral bit-field (9.6) can be converted to an
1813 // rvalue of type int if int can represent all the values of the
1814 // bit-field; otherwise, it can be converted to unsigned int if
1815 // unsigned int can represent all the values of the bit-field. If
1816 // the bit-field is larger yet, no integral promotion applies to
1817 // it. If the bit-field has an enumerated type, it is treated as any
1818 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001819 // FIXME: We should delay checking of bit-fields until we actually perform the
1820 // conversion.
Richard Smith88f4bba2015-03-26 00:16:07 +00001821 if (From) {
John McCalld25db7e2013-05-06 21:39:12 +00001822 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Richard Smith88f4bba2015-03-26 00:16:07 +00001823 llvm::APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001824 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001825 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
Richard Smith88f4bba2015-03-26 00:16:07 +00001826 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
Douglas Gregor71235ec2009-05-02 02:18:30 +00001827 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001828
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001829 // Are we promoting to an int from a bitfield that fits in an int?
1830 if (BitWidth < ToSize ||
1831 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1832 return To->getKind() == BuiltinType::Int;
1833 }
Mike Stump11289f42009-09-09 15:08:12 +00001834
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001835 // Are we promoting to an unsigned int from an unsigned bitfield
1836 // that fits into an unsigned int?
1837 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1838 return To->getKind() == BuiltinType::UInt;
1839 }
Mike Stump11289f42009-09-09 15:08:12 +00001840
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001841 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001842 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001843 }
Richard Smith88f4bba2015-03-26 00:16:07 +00001844 }
Mike Stump11289f42009-09-09 15:08:12 +00001845
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001846 // An rvalue of type bool can be converted to an rvalue of type int,
1847 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001848 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001849 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001850 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001851
1852 return false;
1853}
1854
1855/// IsFloatingPointPromotion - Determines whether the conversion from
1856/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1857/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001858bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001859 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1860 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001861 /// An rvalue of type float can be converted to an rvalue of type
1862 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001863 if (FromBuiltin->getKind() == BuiltinType::Float &&
1864 ToBuiltin->getKind() == BuiltinType::Double)
1865 return true;
1866
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001867 // C99 6.3.1.5p1:
1868 // When a float is promoted to double or long double, or a
1869 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00001870 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001871 (FromBuiltin->getKind() == BuiltinType::Float ||
1872 FromBuiltin->getKind() == BuiltinType::Double) &&
1873 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1874 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001875
1876 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00001877 if (!getLangOpts().NativeHalfType &&
1878 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001879 ToBuiltin->getKind() == BuiltinType::Float)
1880 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001881 }
1882
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001883 return false;
1884}
1885
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001886/// \brief Determine if a conversion is a complex promotion.
1887///
1888/// A complex promotion is defined as a complex -> complex conversion
1889/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001890/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001891bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001892 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001893 if (!FromComplex)
1894 return false;
1895
John McCall9dd450b2009-09-21 23:43:11 +00001896 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001897 if (!ToComplex)
1898 return false;
1899
1900 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001901 ToComplex->getElementType()) ||
Craig Topperc3ec1492014-05-26 06:22:03 +00001902 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001903 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001904}
1905
Douglas Gregor237f96c2008-11-26 23:31:11 +00001906/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1907/// the pointer type FromPtr to a pointer to type ToPointee, with the
1908/// same type qualifiers as FromPtr has on its pointee type. ToType,
1909/// if non-empty, will be a pointer to ToType that may or may not have
1910/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001911///
Mike Stump11289f42009-09-09 15:08:12 +00001912static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001913BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001914 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001915 ASTContext &Context,
1916 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001917 assert((FromPtr->getTypeClass() == Type::Pointer ||
1918 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1919 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001920
John McCall31168b02011-06-15 23:02:42 +00001921 /// Conversions to 'id' subsume cv-qualifier conversions.
1922 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001923 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001924
1925 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001926 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001927 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001928 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001929
John McCall31168b02011-06-15 23:02:42 +00001930 if (StripObjCLifetime)
1931 Quals.removeObjCLifetime();
1932
Mike Stump11289f42009-09-09 15:08:12 +00001933 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001934 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001935 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001936 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001937 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001938
1939 // Build a pointer to ToPointee. It has the right qualifiers
1940 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001941 if (isa<ObjCObjectPointerType>(ToType))
1942 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001943 return Context.getPointerType(ToPointee);
1944 }
1945
1946 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001947 QualType QualifiedCanonToPointee
1948 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001949
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001950 if (isa<ObjCObjectPointerType>(ToType))
1951 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1952 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001953}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001954
Mike Stump11289f42009-09-09 15:08:12 +00001955static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001956 bool InOverloadResolution,
1957 ASTContext &Context) {
1958 // Handle value-dependent integral null pointer constants correctly.
1959 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1960 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001961 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001962 return !InOverloadResolution;
1963
Douglas Gregor56751b52009-09-25 04:25:58 +00001964 return Expr->isNullPointerConstant(Context,
1965 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1966 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001967}
Mike Stump11289f42009-09-09 15:08:12 +00001968
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001969/// IsPointerConversion - Determines whether the conversion of the
1970/// expression From, which has the (possibly adjusted) type FromType,
1971/// can be converted to the type ToType via a pointer conversion (C++
1972/// 4.10). If so, returns true and places the converted type (that
1973/// might differ from ToType in its cv-qualifiers at some level) into
1974/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001975///
Douglas Gregora29dc052008-11-27 01:19:21 +00001976/// This routine also supports conversions to and from block pointers
1977/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1978/// pointers to interfaces. FIXME: Once we've determined the
1979/// appropriate overloading rules for Objective-C, we may want to
1980/// split the Objective-C checks into a different routine; however,
1981/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001982/// conversions, so for now they live here. IncompatibleObjC will be
1983/// set if the conversion is an allowed Objective-C conversion that
1984/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001985bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001986 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001987 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001988 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001989 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001990 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1991 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001992 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001993
Mike Stump11289f42009-09-09 15:08:12 +00001994 // Conversion from a null pointer constant to any Objective-C pointer type.
1995 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001996 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001997 ConvertedType = ToType;
1998 return true;
1999 }
2000
Douglas Gregor231d1c62008-11-27 00:15:41 +00002001 // Blocks: Block pointers can be converted to void*.
2002 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002003 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002004 ConvertedType = ToType;
2005 return true;
2006 }
2007 // Blocks: A null pointer constant can be converted to a block
2008 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002009 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002010 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002011 ConvertedType = ToType;
2012 return true;
2013 }
2014
Sebastian Redl576fd422009-05-10 18:38:11 +00002015 // If the left-hand-side is nullptr_t, the right side can be a null
2016 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002017 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002018 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002019 ConvertedType = ToType;
2020 return true;
2021 }
2022
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002023 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002024 if (!ToTypePtr)
2025 return false;
2026
2027 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002028 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002029 ConvertedType = ToType;
2030 return true;
2031 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002032
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002033 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002034 // , including objective-c pointers.
2035 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002036 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002037 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002038 ConvertedType = BuildSimilarlyQualifiedPointerType(
2039 FromType->getAs<ObjCObjectPointerType>(),
2040 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002041 ToType, Context);
2042 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002043 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002044 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002045 if (!FromTypePtr)
2046 return false;
2047
2048 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002049
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002050 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002051 // pointer conversion, so don't do all of the work below.
2052 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2053 return false;
2054
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002055 // An rvalue of type "pointer to cv T," where T is an object type,
2056 // can be converted to an rvalue of type "pointer to cv void" (C++
2057 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002058 if (FromPointeeType->isIncompleteOrObjectType() &&
2059 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002060 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002061 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002062 ToType, Context,
2063 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002064 return true;
2065 }
2066
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002067 // MSVC allows implicit function to void* type conversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002068 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002069 ToPointeeType->isVoidType()) {
2070 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2071 ToPointeeType,
2072 ToType, Context);
2073 return true;
2074 }
2075
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002076 // When we're overloading in C, we allow a special kind of pointer
2077 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002078 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002079 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002080 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002081 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002082 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002083 return true;
2084 }
2085
Douglas Gregor5c407d92008-10-23 00:40:37 +00002086 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002087 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002088 // An rvalue of type "pointer to cv D," where D is a class type,
2089 // can be converted to an rvalue of type "pointer to cv B," where
2090 // B is a base class (clause 10) of D. If B is an inaccessible
2091 // (clause 11) or ambiguous (10.2) base class of D, a program that
2092 // necessitates this conversion is ill-formed. The result of the
2093 // conversion is a pointer to the base class sub-object of the
2094 // derived class object. The null pointer value is converted to
2095 // the null pointer value of the destination type.
2096 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002097 // Note that we do not check for ambiguity or inaccessibility
2098 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002099 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002100 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002101 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002102 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00002103 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002104 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002105 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002106 ToType, Context);
2107 return true;
2108 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002109
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002110 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2111 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2112 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2113 ToPointeeType,
2114 ToType, Context);
2115 return true;
2116 }
2117
Douglas Gregora119f102008-12-19 19:13:09 +00002118 return false;
2119}
Douglas Gregoraec25842011-04-26 23:16:46 +00002120
2121/// \brief Adopt the given qualifiers for the given type.
2122static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2123 Qualifiers TQs = T.getQualifiers();
2124
2125 // Check whether qualifiers already match.
2126 if (TQs == Qs)
2127 return T;
2128
2129 if (Qs.compatiblyIncludes(TQs))
2130 return Context.getQualifiedType(T, Qs);
2131
2132 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2133}
Douglas Gregora119f102008-12-19 19:13:09 +00002134
2135/// isObjCPointerConversion - Determines whether this is an
2136/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2137/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002138bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002139 QualType& ConvertedType,
2140 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002141 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002142 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002143
Douglas Gregoraec25842011-04-26 23:16:46 +00002144 // The set of qualifiers on the type we're converting from.
2145 Qualifiers FromQualifiers = FromType.getQualifiers();
2146
Steve Naroff7cae42b2009-07-10 23:34:53 +00002147 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002148 const ObjCObjectPointerType* ToObjCPtr =
2149 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002150 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002151 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002152
Steve Naroff7cae42b2009-07-10 23:34:53 +00002153 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002154 // If the pointee types are the same (ignoring qualifications),
2155 // then this is not a pointer conversion.
2156 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2157 FromObjCPtr->getPointeeType()))
2158 return false;
2159
Douglas Gregorab209d82015-07-07 03:58:42 +00002160 // Conversion between Objective-C pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002161 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002162 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2163 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002164 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002165 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2166 FromObjCPtr->getPointeeType()))
2167 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002168 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002169 ToObjCPtr->getPointeeType(),
2170 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002171 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002172 return true;
2173 }
2174
2175 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2176 // Okay: this is some kind of implicit downcast of Objective-C
2177 // interfaces, which is permitted. However, we're going to
2178 // complain about it.
2179 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002180 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002181 ToObjCPtr->getPointeeType(),
2182 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002183 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002184 return true;
2185 }
Mike Stump11289f42009-09-09 15:08:12 +00002186 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002187 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002188 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002189 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002190 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002191 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002192 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002193 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002194 // to a block pointer type.
2195 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002196 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002197 return true;
2198 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002199 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002200 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002201 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002202 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002203 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002204 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002205 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002206 return true;
2207 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002208 else
Douglas Gregora119f102008-12-19 19:13:09 +00002209 return false;
2210
Douglas Gregor033f56d2008-12-23 00:53:59 +00002211 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002212 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002213 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002214 else if (const BlockPointerType *FromBlockPtr =
2215 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002216 FromPointeeType = FromBlockPtr->getPointeeType();
2217 else
Douglas Gregora119f102008-12-19 19:13:09 +00002218 return false;
2219
Douglas Gregora119f102008-12-19 19:13:09 +00002220 // If we have pointers to pointers, recursively check whether this
2221 // is an Objective-C conversion.
2222 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2223 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2224 IncompatibleObjC)) {
2225 // We always complain about this conversion.
2226 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002227 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002228 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002229 return true;
2230 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002231 // Allow conversion of pointee being objective-c pointer to another one;
2232 // as in I* to id.
2233 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2234 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2235 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2236 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002237
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002238 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002239 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002240 return true;
2241 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002242
Douglas Gregor033f56d2008-12-23 00:53:59 +00002243 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002244 // differences in the argument and result types are in Objective-C
2245 // pointer conversions. If so, we permit the conversion (but
2246 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002247 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002248 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002249 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002250 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002251 if (FromFunctionType && ToFunctionType) {
2252 // If the function types are exactly the same, this isn't an
2253 // Objective-C pointer conversion.
2254 if (Context.getCanonicalType(FromPointeeType)
2255 == Context.getCanonicalType(ToPointeeType))
2256 return false;
2257
2258 // Perform the quick checks that will tell us whether these
2259 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002260 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002261 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2262 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2263 return false;
2264
2265 bool HasObjCConversion = false;
Alp Toker314cc812014-01-25 16:55:45 +00002266 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2267 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregora119f102008-12-19 19:13:09 +00002268 // Okay, the types match exactly. Nothing to do.
Alp Toker314cc812014-01-25 16:55:45 +00002269 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2270 ToFunctionType->getReturnType(),
Douglas Gregora119f102008-12-19 19:13:09 +00002271 ConvertedType, IncompatibleObjC)) {
2272 // Okay, we have an Objective-C pointer conversion.
2273 HasObjCConversion = true;
2274 } else {
2275 // Function types are too different. Abort.
2276 return false;
2277 }
Mike Stump11289f42009-09-09 15:08:12 +00002278
Douglas Gregora119f102008-12-19 19:13:09 +00002279 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002280 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002281 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002282 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2283 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002284 if (Context.getCanonicalType(FromArgType)
2285 == Context.getCanonicalType(ToArgType)) {
2286 // Okay, the types match exactly. Nothing to do.
2287 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2288 ConvertedType, IncompatibleObjC)) {
2289 // Okay, we have an Objective-C pointer conversion.
2290 HasObjCConversion = true;
2291 } else {
2292 // Argument types are too different. Abort.
2293 return false;
2294 }
2295 }
2296
2297 if (HasObjCConversion) {
2298 // We had an Objective-C conversion. Allow this pointer
2299 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002300 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002301 IncompatibleObjC = true;
2302 return true;
2303 }
2304 }
2305
Sebastian Redl72b597d2009-01-25 19:43:20 +00002306 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002307}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002308
John McCall31168b02011-06-15 23:02:42 +00002309/// \brief Determine whether this is an Objective-C writeback conversion,
2310/// used for parameter passing when performing automatic reference counting.
2311///
2312/// \param FromType The type we're converting form.
2313///
2314/// \param ToType The type we're converting to.
2315///
2316/// \param ConvertedType The type that will be produced after applying
2317/// this conversion.
2318bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2319 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002320 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002321 Context.hasSameUnqualifiedType(FromType, ToType))
2322 return false;
2323
2324 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2325 QualType ToPointee;
2326 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2327 ToPointee = ToPointer->getPointeeType();
2328 else
2329 return false;
2330
2331 Qualifiers ToQuals = ToPointee.getQualifiers();
2332 if (!ToPointee->isObjCLifetimeType() ||
2333 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002334 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002335 return false;
2336
2337 // Argument must be a pointer to __strong to __weak.
2338 QualType FromPointee;
2339 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2340 FromPointee = FromPointer->getPointeeType();
2341 else
2342 return false;
2343
2344 Qualifiers FromQuals = FromPointee.getQualifiers();
2345 if (!FromPointee->isObjCLifetimeType() ||
2346 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2347 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2348 return false;
2349
2350 // Make sure that we have compatible qualifiers.
2351 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2352 if (!ToQuals.compatiblyIncludes(FromQuals))
2353 return false;
2354
2355 // Remove qualifiers from the pointee type we're converting from; they
2356 // aren't used in the compatibility check belong, and we'll be adding back
2357 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2358 FromPointee = FromPointee.getUnqualifiedType();
2359
2360 // The unqualified form of the pointee types must be compatible.
2361 ToPointee = ToPointee.getUnqualifiedType();
2362 bool IncompatibleObjC;
2363 if (Context.typesAreCompatible(FromPointee, ToPointee))
2364 FromPointee = ToPointee;
2365 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2366 IncompatibleObjC))
2367 return false;
2368
2369 /// \brief Construct the type we're converting to, which is a pointer to
2370 /// __autoreleasing pointee.
2371 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2372 ConvertedType = Context.getPointerType(FromPointee);
2373 return true;
2374}
2375
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002376bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2377 QualType& ConvertedType) {
2378 QualType ToPointeeType;
2379 if (const BlockPointerType *ToBlockPtr =
2380 ToType->getAs<BlockPointerType>())
2381 ToPointeeType = ToBlockPtr->getPointeeType();
2382 else
2383 return false;
2384
2385 QualType FromPointeeType;
2386 if (const BlockPointerType *FromBlockPtr =
2387 FromType->getAs<BlockPointerType>())
2388 FromPointeeType = FromBlockPtr->getPointeeType();
2389 else
2390 return false;
2391 // We have pointer to blocks, check whether the only
2392 // differences in the argument and result types are in Objective-C
2393 // pointer conversions. If so, we permit the conversion.
2394
2395 const FunctionProtoType *FromFunctionType
2396 = FromPointeeType->getAs<FunctionProtoType>();
2397 const FunctionProtoType *ToFunctionType
2398 = ToPointeeType->getAs<FunctionProtoType>();
2399
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002400 if (!FromFunctionType || !ToFunctionType)
2401 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002402
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002403 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002404 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002405
2406 // Perform the quick checks that will tell us whether these
2407 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002408 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002409 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2410 return false;
2411
2412 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2413 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2414 if (FromEInfo != ToEInfo)
2415 return false;
2416
2417 bool IncompatibleObjC = false;
Alp Toker314cc812014-01-25 16:55:45 +00002418 if (Context.hasSameType(FromFunctionType->getReturnType(),
2419 ToFunctionType->getReturnType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002420 // Okay, the types match exactly. Nothing to do.
2421 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002422 QualType RHS = FromFunctionType->getReturnType();
2423 QualType LHS = ToFunctionType->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002424 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002425 !RHS.hasQualifiers() && LHS.hasQualifiers())
2426 LHS = LHS.getUnqualifiedType();
2427
2428 if (Context.hasSameType(RHS,LHS)) {
2429 // OK exact match.
2430 } else if (isObjCPointerConversion(RHS, LHS,
2431 ConvertedType, IncompatibleObjC)) {
2432 if (IncompatibleObjC)
2433 return false;
2434 // Okay, we have an Objective-C pointer conversion.
2435 }
2436 else
2437 return false;
2438 }
2439
2440 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002441 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002442 ArgIdx != NumArgs; ++ArgIdx) {
2443 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002444 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2445 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002446 if (Context.hasSameType(FromArgType, ToArgType)) {
2447 // Okay, the types match exactly. Nothing to do.
2448 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2449 ConvertedType, IncompatibleObjC)) {
2450 if (IncompatibleObjC)
2451 return false;
2452 // Okay, we have an Objective-C pointer conversion.
2453 } else
2454 // Argument types are too different. Abort.
2455 return false;
2456 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002457 if (LangOpts.ObjCAutoRefCount &&
2458 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2459 ToFunctionType))
2460 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002461
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002462 ConvertedType = ToType;
2463 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002464}
2465
Richard Trieucaff2472011-11-23 22:32:32 +00002466enum {
2467 ft_default,
2468 ft_different_class,
2469 ft_parameter_arity,
2470 ft_parameter_mismatch,
2471 ft_return_type,
2472 ft_qualifer_mismatch
2473};
2474
2475/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2476/// function types. Catches different number of parameter, mismatch in
2477/// parameter types, and different return types.
2478void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2479 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002480 // If either type is not valid, include no extra info.
2481 if (FromType.isNull() || ToType.isNull()) {
2482 PDiag << ft_default;
2483 return;
2484 }
2485
Richard Trieucaff2472011-11-23 22:32:32 +00002486 // Get the function type from the pointers.
2487 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2488 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2489 *ToMember = ToType->getAs<MemberPointerType>();
Richard Trieu9098c9f2014-05-22 01:39:16 +00002490 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
Richard Trieucaff2472011-11-23 22:32:32 +00002491 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2492 << QualType(FromMember->getClass(), 0);
2493 return;
2494 }
2495 FromType = FromMember->getPointeeType();
2496 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002497 }
2498
Richard Trieu96ed5b62011-12-13 23:19:45 +00002499 if (FromType->isPointerType())
2500 FromType = FromType->getPointeeType();
2501 if (ToType->isPointerType())
2502 ToType = ToType->getPointeeType();
2503
2504 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002505 FromType = FromType.getNonReferenceType();
2506 ToType = ToType.getNonReferenceType();
2507
Richard Trieucaff2472011-11-23 22:32:32 +00002508 // Don't print extra info for non-specialized template functions.
2509 if (FromType->isInstantiationDependentType() &&
2510 !FromType->getAs<TemplateSpecializationType>()) {
2511 PDiag << ft_default;
2512 return;
2513 }
2514
Richard Trieu96ed5b62011-12-13 23:19:45 +00002515 // No extra info for same types.
2516 if (Context.hasSameType(FromType, ToType)) {
2517 PDiag << ft_default;
2518 return;
2519 }
2520
Richard Trieucaff2472011-11-23 22:32:32 +00002521 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2522 *ToFunction = ToType->getAs<FunctionProtoType>();
2523
2524 // Both types need to be function types.
2525 if (!FromFunction || !ToFunction) {
2526 PDiag << ft_default;
2527 return;
2528 }
2529
Alp Toker9cacbab2014-01-20 20:26:09 +00002530 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2531 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2532 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002533 return;
2534 }
2535
2536 // Handle different parameter types.
2537 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002538 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002539 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002540 << ToFunction->getParamType(ArgPos)
2541 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002542 return;
2543 }
2544
2545 // Handle different return type.
Alp Toker314cc812014-01-25 16:55:45 +00002546 if (!Context.hasSameType(FromFunction->getReturnType(),
2547 ToFunction->getReturnType())) {
2548 PDiag << ft_return_type << ToFunction->getReturnType()
2549 << FromFunction->getReturnType();
Richard Trieucaff2472011-11-23 22:32:32 +00002550 return;
2551 }
2552
2553 unsigned FromQuals = FromFunction->getTypeQuals(),
2554 ToQuals = ToFunction->getTypeQuals();
2555 if (FromQuals != ToQuals) {
2556 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2557 return;
2558 }
2559
2560 // Unable to find a difference, so add no extra info.
2561 PDiag << ft_default;
2562}
2563
Alp Toker9cacbab2014-01-20 20:26:09 +00002564/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002565/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002566/// they have same number of arguments. If the parameters are different,
2567/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002568bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2569 const FunctionProtoType *NewType,
2570 unsigned *ArgPos) {
2571 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2572 N = NewType->param_type_begin(),
2573 E = OldType->param_type_end();
2574 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002575 if (!Context.hasSameType(O->getUnqualifiedType(),
2576 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002577 if (ArgPos)
2578 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002579 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002580 }
2581 }
2582 return true;
2583}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002584
Douglas Gregor39c16d42008-10-24 04:54:22 +00002585/// CheckPointerConversion - Check the pointer conversion from the
2586/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002587/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002588/// conversions for which IsPointerConversion has already returned
2589/// true. It returns true and produces a diagnostic if there was an
2590/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002591bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002592 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002593 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002594 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002595 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002596 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002597
John McCall8cb679e2010-11-15 09:13:47 +00002598 Kind = CK_BitCast;
2599
David Blaikie1c7c8f72012-08-08 17:33:31 +00002600 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
Argyrios Kyrtzidis3e3305d2014-02-02 05:26:43 +00002601 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
David Blaikie1c7c8f72012-08-08 17:33:31 +00002602 Expr::NPCK_ZeroExpression) {
2603 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2604 DiagRuntimeBehavior(From->getExprLoc(), From,
2605 PDiag(diag::warn_impcast_bool_to_null_pointer)
2606 << ToType << From->getSourceRange());
2607 else if (!isUnevaluatedContext())
2608 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2609 << ToType << From->getSourceRange();
2610 }
John McCall9320b872011-09-09 05:25:32 +00002611 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2612 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002613 QualType FromPointeeType = FromPtrType->getPointeeType(),
2614 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002615
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002616 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2617 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002618 // We must have a derived-to-base conversion. Check an
2619 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002620 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2621 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002622 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002623 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002624 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002625
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002626 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002627 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002628 }
2629 }
John McCall9320b872011-09-09 05:25:32 +00002630 } else if (const ObjCObjectPointerType *ToPtrType =
2631 ToType->getAs<ObjCObjectPointerType>()) {
2632 if (const ObjCObjectPointerType *FromPtrType =
2633 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002634 // Objective-C++ conversions are always okay.
2635 // FIXME: We should have a different class of conversions for the
2636 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002637 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002638 return false;
John McCall9320b872011-09-09 05:25:32 +00002639 } else if (FromType->isBlockPointerType()) {
2640 Kind = CK_BlockPointerToObjCPointerCast;
2641 } else {
2642 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002643 }
John McCall9320b872011-09-09 05:25:32 +00002644 } else if (ToType->isBlockPointerType()) {
2645 if (!FromType->isBlockPointerType())
2646 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002647 }
John McCall8cb679e2010-11-15 09:13:47 +00002648
2649 // We shouldn't fall into this case unless it's valid for other
2650 // reasons.
2651 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2652 Kind = CK_NullToPointer;
2653
Douglas Gregor39c16d42008-10-24 04:54:22 +00002654 return false;
2655}
2656
Sebastian Redl72b597d2009-01-25 19:43:20 +00002657/// IsMemberPointerConversion - Determines whether the conversion of the
2658/// expression From, which has the (possibly adjusted) type FromType, can be
2659/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2660/// If so, returns true and places the converted type (that might differ from
2661/// ToType in its cv-qualifiers at some level) into ConvertedType.
2662bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002663 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002664 bool InOverloadResolution,
2665 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002666 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002667 if (!ToTypePtr)
2668 return false;
2669
2670 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002671 if (From->isNullPointerConstant(Context,
2672 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2673 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002674 ConvertedType = ToType;
2675 return true;
2676 }
2677
2678 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002679 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002680 if (!FromTypePtr)
2681 return false;
2682
2683 // A pointer to member of B can be converted to a pointer to member of D,
2684 // where D is derived from B (C++ 4.11p2).
2685 QualType FromClass(FromTypePtr->getClass(), 0);
2686 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002687
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002688 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002689 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002690 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002691 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2692 ToClass.getTypePtr());
2693 return true;
2694 }
2695
2696 return false;
2697}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002698
Sebastian Redl72b597d2009-01-25 19:43:20 +00002699/// CheckMemberPointerConversion - Check the member pointer conversion from the
2700/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002701/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002702/// for which IsMemberPointerConversion has already returned true. It returns
2703/// true and produces a diagnostic if there was an error, or returns false
2704/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002705bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002706 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002707 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002708 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002709 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002710 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002711 if (!FromPtrType) {
2712 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002713 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002714 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002715 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002716 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002717 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002718 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002719
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002720 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002721 assert(ToPtrType && "No member pointer cast has a target type "
2722 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002723
Sebastian Redled8f2002009-01-28 18:33:18 +00002724 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2725 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002726
Sebastian Redled8f2002009-01-28 18:33:18 +00002727 // FIXME: What about dependent types?
2728 assert(FromClass->isRecordType() && "Pointer into non-class.");
2729 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002730
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002731 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002732 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002733 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2734 assert(DerivationOkay &&
2735 "Should not have been called if derivation isn't OK.");
2736 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002737
Sebastian Redled8f2002009-01-28 18:33:18 +00002738 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2739 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002740 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2741 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2742 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2743 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002744 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002745
Douglas Gregor89ee6822009-02-28 01:32:25 +00002746 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002747 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2748 << FromClass << ToClass << QualType(VBase, 0)
2749 << From->getSourceRange();
2750 return true;
2751 }
2752
John McCall5b0829a2010-02-10 09:31:12 +00002753 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002754 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2755 Paths.front(),
2756 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002757
Anders Carlssond7923c62009-08-22 23:33:40 +00002758 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002759 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002760 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002761 return false;
2762}
2763
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002764/// Determine whether the lifetime conversion between the two given
2765/// qualifiers sets is nontrivial.
2766static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2767 Qualifiers ToQuals) {
2768 // Converting anything to const __unsafe_unretained is trivial.
2769 if (ToQuals.hasConst() &&
2770 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2771 return false;
2772
2773 return true;
2774}
2775
Douglas Gregor9a657932008-10-21 23:43:52 +00002776/// IsQualificationConversion - Determines whether the conversion from
2777/// an rvalue of type FromType to ToType is a qualification conversion
2778/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002779///
2780/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2781/// when the qualification conversion involves a change in the Objective-C
2782/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002783bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002784Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002785 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002786 FromType = Context.getCanonicalType(FromType);
2787 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002788 ObjCLifetimeConversion = false;
2789
Douglas Gregor9a657932008-10-21 23:43:52 +00002790 // If FromType and ToType are the same type, this is not a
2791 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002792 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002793 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002794
Douglas Gregor9a657932008-10-21 23:43:52 +00002795 // (C++ 4.4p4):
2796 // A conversion can add cv-qualifiers at levels other than the first
2797 // in multi-level pointers, subject to the following rules: [...]
2798 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002799 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002800 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002801 // Within each iteration of the loop, we check the qualifiers to
2802 // determine if this still looks like a qualification
2803 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002804 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002805 // until there are no more pointers or pointers-to-members left to
2806 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002807 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002808
Douglas Gregor90609aa2011-04-25 18:40:17 +00002809 Qualifiers FromQuals = FromType.getQualifiers();
2810 Qualifiers ToQuals = ToType.getQualifiers();
2811
John McCall31168b02011-06-15 23:02:42 +00002812 // Objective-C ARC:
2813 // Check Objective-C lifetime conversions.
2814 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2815 UnwrappedAnyPointer) {
2816 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002817 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2818 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00002819 FromQuals.removeObjCLifetime();
2820 ToQuals.removeObjCLifetime();
2821 } else {
2822 // Qualification conversions cannot cast between different
2823 // Objective-C lifetime qualifiers.
2824 return false;
2825 }
2826 }
2827
Douglas Gregorf30053d2011-05-08 06:09:53 +00002828 // Allow addition/removal of GC attributes but not changing GC attributes.
2829 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2830 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2831 FromQuals.removeObjCGCAttr();
2832 ToQuals.removeObjCGCAttr();
2833 }
2834
Douglas Gregor9a657932008-10-21 23:43:52 +00002835 // -- for every j > 0, if const is in cv 1,j then const is in cv
2836 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002837 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002838 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002839
Douglas Gregor9a657932008-10-21 23:43:52 +00002840 // -- if the cv 1,j and cv 2,j are different, then const is in
2841 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002842 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002843 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002844 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002845
Douglas Gregor9a657932008-10-21 23:43:52 +00002846 // Keep track of whether all prior cv-qualifiers in the "to" type
2847 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002848 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002849 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002850 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002851
2852 // We are left with FromType and ToType being the pointee types
2853 // after unwrapping the original FromType and ToType the same number
2854 // of types. If we unwrapped any pointers, and if FromType and
2855 // ToType have the same unqualified type (since we checked
2856 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002857 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002858}
2859
Douglas Gregorc79862f2012-04-12 17:51:55 +00002860/// \brief - Determine whether this is a conversion from a scalar type to an
2861/// atomic type.
2862///
2863/// If successful, updates \c SCS's second and third steps in the conversion
2864/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00002865static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2866 bool InOverloadResolution,
2867 StandardConversionSequence &SCS,
2868 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00002869 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2870 if (!ToAtomic)
2871 return false;
2872
2873 StandardConversionSequence InnerSCS;
2874 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2875 InOverloadResolution, InnerSCS,
2876 CStyle, /*AllowObjCWritebackConversion=*/false))
2877 return false;
2878
2879 SCS.Second = InnerSCS.Second;
2880 SCS.setToType(1, InnerSCS.getToType(1));
2881 SCS.Third = InnerSCS.Third;
2882 SCS.QualificationIncludesObjCLifetime
2883 = InnerSCS.QualificationIncludesObjCLifetime;
2884 SCS.setToType(2, InnerSCS.getToType(2));
2885 return true;
2886}
2887
Sebastian Redle5417162012-03-27 18:33:03 +00002888static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2889 CXXConstructorDecl *Constructor,
2890 QualType Type) {
2891 const FunctionProtoType *CtorType =
2892 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002893 if (CtorType->getNumParams() > 0) {
2894 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00002895 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2896 return true;
2897 }
2898 return false;
2899}
2900
Sebastian Redl82ace982012-02-11 23:51:08 +00002901static OverloadingResult
2902IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2903 CXXRecordDecl *To,
2904 UserDefinedConversionSequence &User,
2905 OverloadCandidateSet &CandidateSet,
2906 bool AllowExplicit) {
David Blaikieff7d47a2012-12-19 00:45:41 +00002907 DeclContext::lookup_result R = S.LookupConstructors(To);
2908 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl82ace982012-02-11 23:51:08 +00002909 Con != ConEnd; ++Con) {
2910 NamedDecl *D = *Con;
2911 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2912
2913 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00002914 CXXConstructorDecl *Constructor = nullptr;
Sebastian Redl82ace982012-02-11 23:51:08 +00002915 FunctionTemplateDecl *ConstructorTmpl
2916 = dyn_cast<FunctionTemplateDecl>(D);
2917 if (ConstructorTmpl)
2918 Constructor
2919 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2920 else
2921 Constructor = cast<CXXConstructorDecl>(D);
2922
2923 bool Usable = !Constructor->isInvalidDecl() &&
2924 S.isInitListConstructor(Constructor) &&
2925 (AllowExplicit || !Constructor->isExplicit());
2926 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00002927 // If the first argument is (a reference to) the target type,
2928 // suppress conversions.
2929 bool SuppressUserConversions =
2930 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl82ace982012-02-11 23:51:08 +00002931 if (ConstructorTmpl)
2932 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00002933 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002934 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002935 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002936 else
2937 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002938 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002939 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002940 }
2941 }
2942
2943 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2944
2945 OverloadCandidateSet::iterator Best;
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00002946 switch (auto Result =
2947 CandidateSet.BestViableFunction(S, From->getLocStart(),
2948 Best, true)) {
2949 case OR_Deleted:
Sebastian Redl82ace982012-02-11 23:51:08 +00002950 case OR_Success: {
2951 // Record the standard conversion we used and the conversion function.
2952 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00002953 QualType ThisType = Constructor->getThisType(S.Context);
2954 // Initializer lists don't have conversions as such.
2955 User.Before.setAsIdentityConversion();
2956 User.HadMultipleCandidates = HadMultipleCandidates;
2957 User.ConversionFunction = Constructor;
2958 User.FoundConversionFunction = Best->FoundDecl;
2959 User.After.setAsIdentityConversion();
2960 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2961 User.After.setAllToTypes(ToType);
Fariborz Jahaniandcf06f42015-04-14 17:21:58 +00002962 return Result;
Sebastian Redl82ace982012-02-11 23:51:08 +00002963 }
2964
2965 case OR_No_Viable_Function:
2966 return OR_No_Viable_Function;
Sebastian Redl82ace982012-02-11 23:51:08 +00002967 case OR_Ambiguous:
2968 return OR_Ambiguous;
2969 }
2970
2971 llvm_unreachable("Invalid OverloadResult!");
2972}
2973
Douglas Gregor576e98c2009-01-30 23:27:23 +00002974/// Determines whether there is a user-defined conversion sequence
2975/// (C++ [over.ics.user]) that converts expression From to the type
2976/// ToType. If such a conversion exists, User will contain the
2977/// user-defined conversion sequence that performs such a conversion
2978/// and this routine will return true. Otherwise, this routine returns
2979/// false and User is unspecified.
2980///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002981/// \param AllowExplicit true if the conversion should consider C++0x
2982/// "explicit" conversion functions as well as non-explicit conversion
2983/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00002984///
2985/// \param AllowObjCConversionOnExplicit true if the conversion should
2986/// allow an extra Objective-C pointer conversion on uses of explicit
2987/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00002988static OverloadingResult
2989IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00002990 UserDefinedConversionSequence &User,
2991 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00002992 bool AllowExplicit,
2993 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00002994 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor4b60a152013-11-07 22:34:54 +00002995
Douglas Gregor5ab11652010-04-17 22:01:05 +00002996 // Whether we will only visit constructors.
2997 bool ConstructorsOnly = false;
2998
2999 // If the type we are conversion to is a class type, enumerate its
3000 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003001 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003002 // C++ [over.match.ctor]p1:
3003 // When objects of class type are direct-initialized (8.5), or
3004 // copy-initialized from an expression of the same or a
3005 // derived class type (8.5), overload resolution selects the
3006 // constructor. [...] For copy-initialization, the candidate
3007 // functions are all the converting constructors (12.3.1) of
3008 // that class. The argument list is the expression-list within
3009 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003010 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003011 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00003012 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003013 ConstructorsOnly = true;
3014
Benjamin Kramer90633e32012-11-23 17:04:52 +00003015 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00003016 // RequireCompleteType may have returned true due to some invalid decl
3017 // during template instantiation, but ToType may be complete enough now
3018 // to try to recover.
3019 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003020 // We're not going to find any constructors.
3021 } else if (CXXRecordDecl *ToRecordDecl
3022 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003023
3024 Expr **Args = &From;
3025 unsigned NumArgs = 1;
3026 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003027 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003028 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003029 OverloadingResult Result = IsInitializerListConstructorConversion(
3030 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3031 if (Result != OR_No_Viable_Function)
3032 return Result;
3033 // Never mind.
3034 CandidateSet.clear();
3035
3036 // If we're list-initializing, we pass the individual elements as
3037 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003038 Args = InitList->getInits();
3039 NumArgs = InitList->getNumInits();
3040 ListInitializing = true;
3041 }
3042
David Blaikieff7d47a2012-12-19 00:45:41 +00003043 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3044 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregor89ee6822009-02-28 01:32:25 +00003045 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003046 NamedDecl *D = *Con;
3047 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3048
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003049 // Find the constructor (which may be a template).
Craig Topperc3ec1492014-05-26 06:22:03 +00003050 CXXConstructorDecl *Constructor = nullptr;
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003051 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00003052 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003053 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003054 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003055 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3056 else
John McCalla0296f72010-03-19 07:35:19 +00003057 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003058
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003059 bool Usable = !Constructor->isInvalidDecl();
3060 if (ListInitializing)
3061 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3062 else
3063 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3064 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003065 bool SuppressUserConversions = !ConstructorsOnly;
3066 if (SuppressUserConversions && ListInitializing) {
3067 SuppressUserConversions = false;
3068 if (NumArgs == 1) {
3069 // If the first argument is (a reference to) the target type,
3070 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003071 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3072 S.Context, Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003073 }
3074 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003075 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00003076 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
Craig Topperc3ec1492014-05-26 06:22:03 +00003077 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003078 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003079 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003080 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003081 // Allow one user-defined conversion when user specifies a
3082 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00003083 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003084 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003085 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003086 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003087 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003088 }
3089 }
3090
Douglas Gregor5ab11652010-04-17 22:01:05 +00003091 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003092 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003093 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003094 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003095 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003096 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003097 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003098 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3099 // Add all of the conversion functions as candidates.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00003100 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3101 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003102 DeclAccessPair FoundDecl = I.getPair();
3103 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003104 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3105 if (isa<UsingShadowDecl>(D))
3106 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3107
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003108 CXXConversionDecl *Conv;
3109 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003110 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3111 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003112 else
John McCallda4458e2010-03-31 01:36:47 +00003113 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003114
3115 if (AllowExplicit || !Conv->isExplicit()) {
3116 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003117 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3118 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003119 CandidateSet,
3120 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003121 else
John McCall5c32be02010-08-24 20:38:10 +00003122 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003123 From, ToType, CandidateSet,
3124 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003125 }
3126 }
3127 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003128 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003129
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003130 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3131
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003132 OverloadCandidateSet::iterator Best;
Richard Smith48372b62015-01-27 03:30:40 +00003133 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(),
3134 Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003135 case OR_Success:
Richard Smith48372b62015-01-27 03:30:40 +00003136 case OR_Deleted:
John McCall5c32be02010-08-24 20:38:10 +00003137 // Record the standard conversion we used and the conversion function.
3138 if (CXXConstructorDecl *Constructor
3139 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3140 // C++ [over.ics.user]p1:
3141 // If the user-defined conversion is specified by a
3142 // constructor (12.3.1), the initial standard conversion
3143 // sequence converts the source type to the type required by
3144 // the argument of the constructor.
3145 //
3146 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003147 if (isa<InitListExpr>(From)) {
3148 // Initializer lists don't have conversions as such.
3149 User.Before.setAsIdentityConversion();
3150 } else {
3151 if (Best->Conversions[0].isEllipsis())
3152 User.EllipsisConversion = true;
3153 else {
3154 User.Before = Best->Conversions[0].Standard;
3155 User.EllipsisConversion = false;
3156 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003157 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003158 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003159 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003160 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003161 User.After.setAsIdentityConversion();
3162 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3163 User.After.setAllToTypes(ToType);
Richard Smith48372b62015-01-27 03:30:40 +00003164 return Result;
David Blaikie8a40f702012-01-17 06:56:22 +00003165 }
3166 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003167 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3168 // C++ [over.ics.user]p1:
3169 //
3170 // [...] If the user-defined conversion is specified by a
3171 // conversion function (12.3.2), the initial standard
3172 // conversion sequence converts the source type to the
3173 // implicit object parameter of the conversion function.
3174 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003175 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003176 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003177 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003178 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003179
John McCall5c32be02010-08-24 20:38:10 +00003180 // C++ [over.ics.user]p2:
3181 // The second standard conversion sequence converts the
3182 // result of the user-defined conversion to the target type
3183 // for the sequence. Since an implicit conversion sequence
3184 // is an initialization, the special rules for
3185 // initialization by user-defined conversion apply when
3186 // selecting the best user-defined conversion for a
3187 // user-defined conversion sequence (see 13.3.3 and
3188 // 13.3.3.1).
3189 User.After = Best->FinalConversion;
Richard Smith48372b62015-01-27 03:30:40 +00003190 return Result;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003191 }
David Blaikie8a40f702012-01-17 06:56:22 +00003192 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003193
John McCall5c32be02010-08-24 20:38:10 +00003194 case OR_No_Viable_Function:
3195 return OR_No_Viable_Function;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003196
John McCall5c32be02010-08-24 20:38:10 +00003197 case OR_Ambiguous:
3198 return OR_Ambiguous;
3199 }
3200
David Blaikie8a40f702012-01-17 06:56:22 +00003201 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003202}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003203
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003204bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003205Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003206 ImplicitConversionSequence ICS;
Richard Smith100b24a2014-04-17 01:52:14 +00003207 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3208 OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003209 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003210 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003211 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003212 if (OvResult == OR_Ambiguous)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003213 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3214 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003215 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003216 if (!RequireCompleteType(From->getLocStart(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003217 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003218 From->getType(), From->getSourceRange()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003219 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
Nick Lewycky08426e22015-08-25 22:18:46 +00003220 << false << From->getType() << From->getSourceRange() << ToType;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003221 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003222 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003223 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003224 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003225}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003226
Douglas Gregor2837aa22012-02-22 17:32:19 +00003227/// \brief Compare the user-defined conversion functions or constructors
3228/// of two user-defined conversion sequences to determine whether any ordering
3229/// is possible.
3230static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003231compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003232 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003233 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003234 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003235
Douglas Gregor2837aa22012-02-22 17:32:19 +00003236 // Objective-C++:
3237 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003238 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003239 // respectively, always prefer the conversion to a function pointer,
3240 // because the function pointer is more lightweight and is more likely
3241 // to keep code working.
Ted Kremenek8d265c22014-04-01 07:23:18 +00003242 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003243 if (!Conv1)
3244 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003245
Douglas Gregor2837aa22012-02-22 17:32:19 +00003246 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3247 if (!Conv2)
3248 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003249
Douglas Gregor2837aa22012-02-22 17:32:19 +00003250 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3251 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3252 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3253 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003254 return Block1 ? ImplicitConversionSequence::Worse
3255 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003256 }
3257
3258 return ImplicitConversionSequence::Indistinguishable;
3259}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003260
3261static bool hasDeprecatedStringLiteralToCharPtrConversion(
3262 const ImplicitConversionSequence &ICS) {
3263 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3264 (ICS.isUserDefined() &&
3265 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3266}
3267
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003268/// CompareImplicitConversionSequences - Compare two implicit
3269/// conversion sequences to determine whether one is better than the
3270/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003271static ImplicitConversionSequence::CompareKind
3272CompareImplicitConversionSequences(Sema &S,
3273 const ImplicitConversionSequence& ICS1,
3274 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003275{
3276 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3277 // conversion sequences (as defined in 13.3.3.1)
3278 // -- a standard conversion sequence (13.3.3.1.1) is a better
3279 // conversion sequence than a user-defined conversion sequence or
3280 // an ellipsis conversion sequence, and
3281 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3282 // conversion sequence than an ellipsis conversion sequence
3283 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003284 //
John McCall0d1da222010-01-12 00:44:57 +00003285 // C++0x [over.best.ics]p10:
3286 // For the purpose of ranking implicit conversion sequences as
3287 // described in 13.3.3.2, the ambiguous conversion sequence is
3288 // treated as a user-defined sequence that is indistinguishable
3289 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003290
3291 // String literal to 'char *' conversion has been deprecated in C++03. It has
3292 // been removed from C++11. We still accept this conversion, if it happens at
3293 // the best viable function. Otherwise, this conversion is considered worse
3294 // than ellipsis conversion. Consider this as an extension; this is not in the
3295 // standard. For example:
3296 //
3297 // int &f(...); // #1
3298 // void f(char*); // #2
3299 // void g() { int &r = f("foo"); }
3300 //
3301 // In C++03, we pick #2 as the best viable function.
3302 // In C++11, we pick #1 as the best viable function, because ellipsis
3303 // conversion is better than string-literal to char* conversion (since there
3304 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3305 // convert arguments, #2 would be the best viable function in C++11.
3306 // If the best viable function has this conversion, a warning will be issued
3307 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3308
3309 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3310 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3311 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3312 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3313 ? ImplicitConversionSequence::Worse
3314 : ImplicitConversionSequence::Better;
3315
Douglas Gregor5ab11652010-04-17 22:01:05 +00003316 if (ICS1.getKindRank() < ICS2.getKindRank())
3317 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003318 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003319 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003320
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003321 // The following checks require both conversion sequences to be of
3322 // the same kind.
3323 if (ICS1.getKind() != ICS2.getKind())
3324 return ImplicitConversionSequence::Indistinguishable;
3325
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003326 ImplicitConversionSequence::CompareKind Result =
3327 ImplicitConversionSequence::Indistinguishable;
3328
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003329 // Two implicit conversion sequences of the same form are
3330 // indistinguishable conversion sequences unless one of the
3331 // following rules apply: (C++ 13.3.3.2p3):
Larisse Voufo19d08672015-01-27 18:47:05 +00003332
3333 // List-initialization sequence L1 is a better conversion sequence than
3334 // list-initialization sequence L2 if:
3335 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3336 // if not that,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00003337 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
Larisse Voufo19d08672015-01-27 18:47:05 +00003338 // and N1 is smaller than N2.,
3339 // even if one of the other rules in this paragraph would otherwise apply.
3340 if (!ICS1.isBad()) {
3341 if (ICS1.isStdInitializerListElement() &&
3342 !ICS2.isStdInitializerListElement())
3343 return ImplicitConversionSequence::Better;
3344 if (!ICS1.isStdInitializerListElement() &&
3345 ICS2.isStdInitializerListElement())
3346 return ImplicitConversionSequence::Worse;
3347 }
3348
John McCall0d1da222010-01-12 00:44:57 +00003349 if (ICS1.isStandard())
Larisse Voufo19d08672015-01-27 18:47:05 +00003350 // Standard conversion sequence S1 is a better conversion sequence than
3351 // standard conversion sequence S2 if [...]
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003352 Result = CompareStandardConversionSequences(S,
3353 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003354 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003355 // User-defined conversion sequence U1 is a better conversion
3356 // sequence than another user-defined conversion sequence U2 if
3357 // they contain the same user-defined conversion function or
3358 // constructor and if the second standard conversion sequence of
3359 // U1 is better than the second standard conversion sequence of
3360 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003361 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003362 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003363 Result = CompareStandardConversionSequences(S,
3364 ICS1.UserDefined.After,
3365 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003366 else
3367 Result = compareConversionFunctions(S,
3368 ICS1.UserDefined.ConversionFunction,
3369 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003370 }
3371
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003372 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003373}
3374
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003375static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3376 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3377 Qualifiers Quals;
3378 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003379 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003380 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003381
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003382 return Context.hasSameUnqualifiedType(T1, T2);
3383}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003384
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003385// Per 13.3.3.2p3, compare the given standard conversion sequences to
3386// determine if one is a proper subset of the other.
3387static ImplicitConversionSequence::CompareKind
3388compareStandardConversionSubsets(ASTContext &Context,
3389 const StandardConversionSequence& SCS1,
3390 const StandardConversionSequence& SCS2) {
3391 ImplicitConversionSequence::CompareKind Result
3392 = ImplicitConversionSequence::Indistinguishable;
3393
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003394 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003395 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003396 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3397 return ImplicitConversionSequence::Better;
3398 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3399 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003400
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003401 if (SCS1.Second != SCS2.Second) {
3402 if (SCS1.Second == ICK_Identity)
3403 Result = ImplicitConversionSequence::Better;
3404 else if (SCS2.Second == ICK_Identity)
3405 Result = ImplicitConversionSequence::Worse;
3406 else
3407 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003408 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003409 return ImplicitConversionSequence::Indistinguishable;
3410
3411 if (SCS1.Third == SCS2.Third) {
3412 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3413 : ImplicitConversionSequence::Indistinguishable;
3414 }
3415
3416 if (SCS1.Third == ICK_Identity)
3417 return Result == ImplicitConversionSequence::Worse
3418 ? ImplicitConversionSequence::Indistinguishable
3419 : ImplicitConversionSequence::Better;
3420
3421 if (SCS2.Third == ICK_Identity)
3422 return Result == ImplicitConversionSequence::Better
3423 ? ImplicitConversionSequence::Indistinguishable
3424 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003425
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003426 return ImplicitConversionSequence::Indistinguishable;
3427}
3428
Douglas Gregore696ebb2011-01-26 14:52:12 +00003429/// \brief Determine whether one of the given reference bindings is better
3430/// than the other based on what kind of bindings they are.
Richard Smith19172c42014-07-14 02:28:44 +00003431static bool
3432isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3433 const StandardConversionSequence &SCS2) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003434 // C++0x [over.ics.rank]p3b4:
3435 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3436 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003437 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003438 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003439 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003440 // reference*.
3441 //
3442 // FIXME: Rvalue references. We're going rogue with the above edits,
3443 // because the semantics in the current C++0x working paper (N3225 at the
3444 // time of this writing) break the standard definition of std::forward
3445 // and std::reference_wrapper when dealing with references to functions.
3446 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003447 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3448 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3449 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003450
Douglas Gregore696ebb2011-01-26 14:52:12 +00003451 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3452 SCS2.IsLvalueReference) ||
3453 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
Richard Smith19172c42014-07-14 02:28:44 +00003454 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
Douglas Gregore696ebb2011-01-26 14:52:12 +00003455}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003456
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003457/// CompareStandardConversionSequences - Compare two standard
3458/// conversion sequences to determine whether one is better than the
3459/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003460static ImplicitConversionSequence::CompareKind
3461CompareStandardConversionSequences(Sema &S,
3462 const StandardConversionSequence& SCS1,
3463 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003464{
3465 // Standard conversion sequence S1 is a better conversion sequence
3466 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3467
3468 // -- S1 is a proper subsequence of S2 (comparing the conversion
3469 // sequences in the canonical form defined by 13.3.3.1.1,
3470 // excluding any Lvalue Transformation; the identity conversion
3471 // sequence is considered to be a subsequence of any
3472 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003473 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003474 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003475 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003476
3477 // -- the rank of S1 is better than the rank of S2 (by the rules
3478 // defined below), or, if not that,
3479 ImplicitConversionRank Rank1 = SCS1.getRank();
3480 ImplicitConversionRank Rank2 = SCS2.getRank();
3481 if (Rank1 < Rank2)
3482 return ImplicitConversionSequence::Better;
3483 else if (Rank2 < Rank1)
3484 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003485
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003486 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3487 // are indistinguishable unless one of the following rules
3488 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003489
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003490 // A conversion that is not a conversion of a pointer, or
3491 // pointer to member, to bool is better than another conversion
3492 // that is such a conversion.
3493 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3494 return SCS2.isPointerConversionToBool()
3495 ? ImplicitConversionSequence::Better
3496 : ImplicitConversionSequence::Worse;
3497
Douglas Gregor5c407d92008-10-23 00:40:37 +00003498 // C++ [over.ics.rank]p4b2:
3499 //
3500 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003501 // conversion of B* to A* is better than conversion of B* to
3502 // void*, and conversion of A* to void* is better than conversion
3503 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003504 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003505 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003506 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003507 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003508 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3509 // Exactly one of the conversion sequences is a conversion to
3510 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003511 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3512 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003513 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3514 // Neither conversion sequence converts to a void pointer; compare
3515 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003516 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00003517 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003518 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003519 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3520 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003521 // Both conversion sequences are conversions to void
3522 // pointers. Compare the source types to determine if there's an
3523 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003524 QualType FromType1 = SCS1.getFromType();
3525 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003526
3527 // Adjust the types we're converting from via the array-to-pointer
3528 // conversion, if we need to.
3529 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003530 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003531 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003532 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003533
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003534 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3535 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003536
John McCall5c32be02010-08-24 20:38:10 +00003537 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003538 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003539 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003540 return ImplicitConversionSequence::Worse;
3541
3542 // Objective-C++: If one interface is more specific than the
3543 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003544 const ObjCObjectPointerType* FromObjCPtr1
3545 = FromType1->getAs<ObjCObjectPointerType>();
3546 const ObjCObjectPointerType* FromObjCPtr2
3547 = FromType2->getAs<ObjCObjectPointerType>();
3548 if (FromObjCPtr1 && FromObjCPtr2) {
3549 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3550 FromObjCPtr2);
3551 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3552 FromObjCPtr1);
3553 if (AssignLeft != AssignRight) {
3554 return AssignLeft? ImplicitConversionSequence::Better
3555 : ImplicitConversionSequence::Worse;
3556 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003557 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003558 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003559
3560 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3561 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003562 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003563 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003564 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003565
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003566 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003567 // Check for a better reference binding based on the kind of bindings.
3568 if (isBetterReferenceBindingKind(SCS1, SCS2))
3569 return ImplicitConversionSequence::Better;
3570 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3571 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003572
Sebastian Redlb28b4072009-03-22 23:49:27 +00003573 // C++ [over.ics.rank]p3b4:
3574 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3575 // which the references refer are the same type except for
3576 // top-level cv-qualifiers, and the type to which the reference
3577 // initialized by S2 refers is more cv-qualified than the type
3578 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003579 QualType T1 = SCS1.getToType(2);
3580 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003581 T1 = S.Context.getCanonicalType(T1);
3582 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003583 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003584 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3585 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003586 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003587 // Objective-C++ ARC: If the references refer to objects with different
3588 // lifetimes, prefer bindings that don't change lifetime.
3589 if (SCS1.ObjCLifetimeConversionBinding !=
3590 SCS2.ObjCLifetimeConversionBinding) {
3591 return SCS1.ObjCLifetimeConversionBinding
3592 ? ImplicitConversionSequence::Worse
3593 : ImplicitConversionSequence::Better;
3594 }
3595
Chandler Carruth8e543b32010-12-12 08:17:55 +00003596 // If the type is an array type, promote the element qualifiers to the
3597 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003598 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003599 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003600 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003601 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003602 if (T2.isMoreQualifiedThan(T1))
3603 return ImplicitConversionSequence::Better;
3604 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003605 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003606 }
3607 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003608
Francois Pichet08d2fa02011-09-18 21:37:37 +00003609 // In Microsoft mode, prefer an integral conversion to a
3610 // floating-to-integral conversion if the integral conversion
3611 // is between types of the same size.
3612 // For example:
3613 // void f(float);
3614 // void f(int);
3615 // int main {
3616 // long a;
3617 // f(a);
3618 // }
3619 // Here, MSVC will call f(int) instead of generating a compile error
3620 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003621 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3622 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003623 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003624 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003625 return ImplicitConversionSequence::Better;
3626
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003627 return ImplicitConversionSequence::Indistinguishable;
3628}
3629
3630/// CompareQualificationConversions - Compares two standard conversion
3631/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003632/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
Richard Smith17c00b42014-11-12 01:24:00 +00003633static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003634CompareQualificationConversions(Sema &S,
3635 const StandardConversionSequence& SCS1,
3636 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003637 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003638 // -- S1 and S2 differ only in their qualification conversion and
3639 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3640 // cv-qualification signature of type T1 is a proper subset of
3641 // the cv-qualification signature of type T2, and S1 is not the
3642 // deprecated string literal array-to-pointer conversion (4.2).
3643 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3644 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3645 return ImplicitConversionSequence::Indistinguishable;
3646
3647 // FIXME: the example in the standard doesn't use a qualification
3648 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003649 QualType T1 = SCS1.getToType(2);
3650 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003651 T1 = S.Context.getCanonicalType(T1);
3652 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003653 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003654 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3655 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003656
3657 // If the types are the same, we won't learn anything by unwrapped
3658 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003659 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003660 return ImplicitConversionSequence::Indistinguishable;
3661
Chandler Carruth607f38e2009-12-29 07:16:59 +00003662 // If the type is an array type, promote the element qualifiers to the type
3663 // for comparison.
3664 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003665 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003666 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003667 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003668
Mike Stump11289f42009-09-09 15:08:12 +00003669 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003670 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003671
3672 // Objective-C++ ARC:
3673 // Prefer qualification conversions not involving a change in lifetime
3674 // to qualification conversions that do not change lifetime.
3675 if (SCS1.QualificationIncludesObjCLifetime !=
3676 SCS2.QualificationIncludesObjCLifetime) {
3677 Result = SCS1.QualificationIncludesObjCLifetime
3678 ? ImplicitConversionSequence::Worse
3679 : ImplicitConversionSequence::Better;
3680 }
3681
John McCall5c32be02010-08-24 20:38:10 +00003682 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003683 // Within each iteration of the loop, we check the qualifiers to
3684 // determine if this still looks like a qualification
3685 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003686 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003687 // until there are no more pointers or pointers-to-members left
3688 // to unwrap. This essentially mimics what
3689 // IsQualificationConversion does, but here we're checking for a
3690 // strict subset of qualifiers.
3691 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3692 // The qualifiers are the same, so this doesn't tell us anything
3693 // about how the sequences rank.
3694 ;
3695 else if (T2.isMoreQualifiedThan(T1)) {
3696 // T1 has fewer qualifiers, so it could be the better sequence.
3697 if (Result == ImplicitConversionSequence::Worse)
3698 // Neither has qualifiers that are a subset of the other's
3699 // qualifiers.
3700 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003701
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003702 Result = ImplicitConversionSequence::Better;
3703 } else if (T1.isMoreQualifiedThan(T2)) {
3704 // T2 has fewer qualifiers, so it could be the better sequence.
3705 if (Result == ImplicitConversionSequence::Better)
3706 // Neither has qualifiers that are a subset of the other's
3707 // qualifiers.
3708 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003709
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003710 Result = ImplicitConversionSequence::Worse;
3711 } else {
3712 // Qualifiers are disjoint.
3713 return ImplicitConversionSequence::Indistinguishable;
3714 }
3715
3716 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003717 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003718 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003719 }
3720
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003721 // Check that the winning standard conversion sequence isn't using
3722 // the deprecated string literal array to pointer conversion.
3723 switch (Result) {
3724 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003725 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003726 Result = ImplicitConversionSequence::Indistinguishable;
3727 break;
3728
3729 case ImplicitConversionSequence::Indistinguishable:
3730 break;
3731
3732 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003733 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003734 Result = ImplicitConversionSequence::Indistinguishable;
3735 break;
3736 }
3737
3738 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003739}
3740
Douglas Gregor5c407d92008-10-23 00:40:37 +00003741/// CompareDerivedToBaseConversions - Compares two standard conversion
3742/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003743/// various kinds of derived-to-base conversions (C++
3744/// [over.ics.rank]p4b3). As part of these checks, we also look at
3745/// conversions between Objective-C interface types.
Richard Smith17c00b42014-11-12 01:24:00 +00003746static ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003747CompareDerivedToBaseConversions(Sema &S,
3748 const StandardConversionSequence& SCS1,
3749 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003750 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003751 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003752 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003753 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003754
3755 // Adjust the types we're converting from via the array-to-pointer
3756 // conversion, if we need to.
3757 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003758 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003759 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003760 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003761
3762 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003763 FromType1 = S.Context.getCanonicalType(FromType1);
3764 ToType1 = S.Context.getCanonicalType(ToType1);
3765 FromType2 = S.Context.getCanonicalType(FromType2);
3766 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003767
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003768 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003769 //
3770 // If class B is derived directly or indirectly from class A and
3771 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003772 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003773 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003774 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003775 SCS2.Second == ICK_Pointer_Conversion &&
3776 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3777 FromType1->isPointerType() && FromType2->isPointerType() &&
3778 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003779 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003780 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003781 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003782 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003783 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003784 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003785 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003786 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003787
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003788 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003789 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003790 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003791 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003792 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003793 return ImplicitConversionSequence::Worse;
3794 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003795
3796 // -- conversion of B* to A* is better than conversion of C* to A*,
3797 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003798 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003799 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003800 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003801 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003802 }
3803 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3804 SCS2.Second == ICK_Pointer_Conversion) {
3805 const ObjCObjectPointerType *FromPtr1
3806 = FromType1->getAs<ObjCObjectPointerType>();
3807 const ObjCObjectPointerType *FromPtr2
3808 = FromType2->getAs<ObjCObjectPointerType>();
3809 const ObjCObjectPointerType *ToPtr1
3810 = ToType1->getAs<ObjCObjectPointerType>();
3811 const ObjCObjectPointerType *ToPtr2
3812 = ToType2->getAs<ObjCObjectPointerType>();
3813
3814 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3815 // Apply the same conversion ranking rules for Objective-C pointer types
3816 // that we do for C++ pointers to class types. However, we employ the
3817 // Objective-C pseudo-subtyping relationship used for assignment of
3818 // Objective-C pointer types.
3819 bool FromAssignLeft
3820 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3821 bool FromAssignRight
3822 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3823 bool ToAssignLeft
3824 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3825 bool ToAssignRight
3826 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3827
3828 // A conversion to an a non-id object pointer type or qualified 'id'
3829 // type is better than a conversion to 'id'.
3830 if (ToPtr1->isObjCIdType() &&
3831 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3832 return ImplicitConversionSequence::Worse;
3833 if (ToPtr2->isObjCIdType() &&
3834 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3835 return ImplicitConversionSequence::Better;
3836
3837 // A conversion to a non-id object pointer type is better than a
3838 // conversion to a qualified 'id' type
3839 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3840 return ImplicitConversionSequence::Worse;
3841 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3842 return ImplicitConversionSequence::Better;
3843
3844 // A conversion to an a non-Class object pointer type or qualified 'Class'
3845 // type is better than a conversion to 'Class'.
3846 if (ToPtr1->isObjCClassType() &&
3847 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3848 return ImplicitConversionSequence::Worse;
3849 if (ToPtr2->isObjCClassType() &&
3850 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3851 return ImplicitConversionSequence::Better;
3852
3853 // A conversion to a non-Class object pointer type is better than a
3854 // conversion to a qualified 'Class' type.
3855 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3856 return ImplicitConversionSequence::Worse;
3857 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3858 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003859
Douglas Gregor058d3de2011-01-31 18:51:41 +00003860 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3861 if (S.Context.hasSameType(FromType1, FromType2) &&
3862 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3863 (ToAssignLeft != ToAssignRight))
3864 return ToAssignLeft? ImplicitConversionSequence::Worse
3865 : ImplicitConversionSequence::Better;
3866
3867 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3868 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3869 (FromAssignLeft != FromAssignRight))
3870 return FromAssignLeft? ImplicitConversionSequence::Better
3871 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003872 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003873 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003874
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003875 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003876 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3877 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3878 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003879 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003880 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003881 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003882 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003883 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003884 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003885 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003886 ToType2->getAs<MemberPointerType>();
3887 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3888 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3889 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3890 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3891 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3892 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3893 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3894 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003895 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003896 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003897 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003898 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003899 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003900 return ImplicitConversionSequence::Better;
3901 }
3902 // conversion of B::* to C::* is better than conversion of A::* to C::*
3903 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003904 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003905 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003906 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003907 return ImplicitConversionSequence::Worse;
3908 }
3909 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003910
Douglas Gregor5ab11652010-04-17 22:01:05 +00003911 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003912 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003913 // -- binding of an expression of type C to a reference of type
3914 // B& is better than binding an expression of type C to a
3915 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003916 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3917 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3918 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003919 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003920 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003921 return ImplicitConversionSequence::Worse;
3922 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003923
Douglas Gregor2fe98832008-11-03 19:09:14 +00003924 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003925 // -- binding of an expression of type B to a reference of type
3926 // A& is better than binding an expression of type C to a
3927 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003928 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3929 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3930 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003931 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003932 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003933 return ImplicitConversionSequence::Worse;
3934 }
3935 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003936
Douglas Gregor5c407d92008-10-23 00:40:37 +00003937 return ImplicitConversionSequence::Indistinguishable;
3938}
3939
Douglas Gregor45bb4832013-03-26 23:36:30 +00003940/// \brief Determine whether the given type is valid, e.g., it is not an invalid
3941/// C++ class.
3942static bool isTypeValid(QualType T) {
3943 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3944 return !Record->isInvalidDecl();
3945
3946 return true;
3947}
3948
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003949/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3950/// determine whether they are reference-related,
3951/// reference-compatible, reference-compatible with added
3952/// qualification, or incompatible, for use in C++ initialization by
3953/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3954/// type, and the first type (T1) is the pointee type of the reference
3955/// type being initialized.
3956Sema::ReferenceCompareResult
3957Sema::CompareReferenceRelationship(SourceLocation Loc,
3958 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003959 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003960 bool &ObjCConversion,
3961 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003962 assert(!OrigT1->isReferenceType() &&
3963 "T1 must be the pointee type of the reference type");
3964 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3965
3966 QualType T1 = Context.getCanonicalType(OrigT1);
3967 QualType T2 = Context.getCanonicalType(OrigT2);
3968 Qualifiers T1Quals, T2Quals;
3969 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3970 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3971
3972 // C++ [dcl.init.ref]p4:
3973 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3974 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3975 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003976 DerivedToBase = false;
3977 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003978 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003979 if (UnqualT1 == UnqualT2) {
3980 // Nothing to do.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003981 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00003982 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
3983 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003984 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003985 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3986 UnqualT2->isObjCObjectOrInterfaceType() &&
3987 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3988 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003989 else
3990 return Ref_Incompatible;
3991
3992 // At this point, we know that T1 and T2 are reference-related (at
3993 // least).
3994
3995 // If the type is an array type, promote the element qualifiers to the type
3996 // for comparison.
3997 if (isa<ArrayType>(T1) && T1Quals)
3998 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3999 if (isa<ArrayType>(T2) && T2Quals)
4000 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4001
4002 // C++ [dcl.init.ref]p4:
4003 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4004 // reference-related to T2 and cv1 is the same cv-qualification
4005 // as, or greater cv-qualification than, cv2. For purposes of
4006 // overload resolution, cases for which cv1 is greater
4007 // cv-qualification than cv2 are identified as
4008 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004009 //
4010 // Note that we also require equivalence of Objective-C GC and address-space
4011 // qualifiers when performing these computations, so that e.g., an int in
4012 // address space 1 is not reference-compatible with an int in address
4013 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004014 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4015 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004016 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4017 ObjCLifetimeConversion = true;
4018
John McCall31168b02011-06-15 23:02:42 +00004019 T1Quals.removeObjCLifetime();
4020 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004021 }
4022
Douglas Gregord517d552011-04-28 17:56:11 +00004023 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004024 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00004025 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004026 return Ref_Compatible_With_Added_Qualification;
4027 else
4028 return Ref_Related;
4029}
4030
Douglas Gregor836a7e82010-08-11 02:15:33 +00004031/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004032/// with DeclType. Return true if something definite is found.
4033static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004034FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4035 QualType DeclType, SourceLocation DeclLoc,
4036 Expr *Init, QualType T2, bool AllowRvalues,
4037 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004038 assert(T2->isRecordType() && "Can only find conversions of record types.");
4039 CXXRecordDecl *T2RecordDecl
4040 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4041
Richard Smith100b24a2014-04-17 01:52:14 +00004042 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00004043 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4044 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004045 NamedDecl *D = *I;
4046 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4047 if (isa<UsingShadowDecl>(D))
4048 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4049
4050 FunctionTemplateDecl *ConvTemplate
4051 = dyn_cast<FunctionTemplateDecl>(D);
4052 CXXConversionDecl *Conv;
4053 if (ConvTemplate)
4054 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4055 else
4056 Conv = cast<CXXConversionDecl>(D);
4057
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004058 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004059 // explicit conversions, skip it.
4060 if (!AllowExplicit && Conv->isExplicit())
4061 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004062
Douglas Gregor836a7e82010-08-11 02:15:33 +00004063 if (AllowRvalues) {
4064 bool DerivedToBase = false;
4065 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004066 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004067
4068 // If we are initializing an rvalue reference, don't permit conversion
4069 // functions that return lvalues.
4070 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4071 const ReferenceType *RefType
4072 = Conv->getConversionType()->getAs<LValueReferenceType>();
4073 if (RefType && !RefType->getPointeeType()->isFunctionType())
4074 continue;
4075 }
4076
Douglas Gregor836a7e82010-08-11 02:15:33 +00004077 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004078 S.CompareReferenceRelationship(
4079 DeclLoc,
4080 Conv->getConversionType().getNonReferenceType()
4081 .getUnqualifiedType(),
4082 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004083 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004084 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004085 continue;
4086 } else {
4087 // If the conversion function doesn't return a reference type,
4088 // it can't be considered for this conversion. An rvalue reference
4089 // is only acceptable if its referencee is a function type.
4090
4091 const ReferenceType *RefType =
4092 Conv->getConversionType()->getAs<ReferenceType>();
4093 if (!RefType ||
4094 (!RefType->isLValueReferenceType() &&
4095 !RefType->getPointeeType()->isFunctionType()))
4096 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004097 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004098
Douglas Gregor836a7e82010-08-11 02:15:33 +00004099 if (ConvTemplate)
4100 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004101 Init, DeclType, CandidateSet,
4102 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004103 else
4104 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004105 DeclType, CandidateSet,
4106 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004107 }
4108
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004109 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4110
Sebastian Redld92badf2010-06-30 18:13:39 +00004111 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004112 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004113 case OR_Success:
4114 // C++ [over.ics.ref]p1:
4115 //
4116 // [...] If the parameter binds directly to the result of
4117 // applying a conversion function to the argument
4118 // expression, the implicit conversion sequence is a
4119 // user-defined conversion sequence (13.3.3.1.2), with the
4120 // second standard conversion sequence either an identity
4121 // conversion or, if the conversion function returns an
4122 // entity of a type that is a derived class of the parameter
4123 // type, a derived-to-base Conversion.
4124 if (!Best->FinalConversion.DirectBinding)
4125 return false;
4126
4127 ICS.setUserDefined();
4128 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4129 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004130 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004131 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004132 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004133 ICS.UserDefined.EllipsisConversion = false;
4134 assert(ICS.UserDefined.After.ReferenceBinding &&
4135 ICS.UserDefined.After.DirectBinding &&
4136 "Expected a direct reference binding!");
4137 return true;
4138
4139 case OR_Ambiguous:
4140 ICS.setAmbiguous();
4141 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4142 Cand != CandidateSet.end(); ++Cand)
4143 if (Cand->Viable)
4144 ICS.Ambiguous.addConversion(Cand->Function);
4145 return true;
4146
4147 case OR_No_Viable_Function:
4148 case OR_Deleted:
4149 // There was no suitable conversion, or we found a deleted
4150 // conversion; continue with other checks.
4151 return false;
4152 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004153
David Blaikie8a40f702012-01-17 06:56:22 +00004154 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004155}
4156
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004157/// \brief Compute an implicit conversion sequence for reference
4158/// initialization.
4159static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004160TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004161 SourceLocation DeclLoc,
4162 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004163 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004164 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4165
4166 // Most paths end in a failed conversion.
4167 ImplicitConversionSequence ICS;
4168 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4169
4170 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4171 QualType T2 = Init->getType();
4172
4173 // If the initializer is the address of an overloaded function, try
4174 // to resolve the overloaded function. If all goes well, T2 is the
4175 // type of the resulting function.
4176 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4177 DeclAccessPair Found;
4178 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4179 false, Found))
4180 T2 = Fn->getType();
4181 }
4182
4183 // Compute some basic properties of the types and the initializer.
4184 bool isRValRef = DeclType->isRValueReferenceType();
4185 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004186 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004187 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004188 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004189 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004190 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004191 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004192
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004193
Sebastian Redld92badf2010-06-30 18:13:39 +00004194 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004195 // A reference to type "cv1 T1" is initialized by an expression
4196 // of type "cv2 T2" as follows:
4197
Sebastian Redld92badf2010-06-30 18:13:39 +00004198 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004199 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004200 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4201 // reference-compatible with "cv2 T2," or
4202 //
4203 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4204 if (InitCategory.isLValue() &&
4205 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004206 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004207 // When a parameter of reference type binds directly (8.5.3)
4208 // to an argument expression, the implicit conversion sequence
4209 // is the identity conversion, unless the argument expression
4210 // has a type that is a derived class of the parameter type,
4211 // in which case the implicit conversion sequence is a
4212 // derived-to-base Conversion (13.3.3.1).
4213 ICS.setStandard();
4214 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004215 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4216 : ObjCConversion? ICK_Compatible_Conversion
4217 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004218 ICS.Standard.Third = ICK_Identity;
4219 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4220 ICS.Standard.setToType(0, T2);
4221 ICS.Standard.setToType(1, T1);
4222 ICS.Standard.setToType(2, T1);
4223 ICS.Standard.ReferenceBinding = true;
4224 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004225 ICS.Standard.IsLvalueReference = !isRValRef;
4226 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4227 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004228 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004229 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004230 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004231 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004232
Sebastian Redld92badf2010-06-30 18:13:39 +00004233 // Nothing more to do: the inaccessibility/ambiguity check for
4234 // derived-to-base conversions is suppressed when we're
4235 // computing the implicit conversion sequence (C++
4236 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004237 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004238 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004239
Sebastian Redld92badf2010-06-30 18:13:39 +00004240 // -- has a class type (i.e., T2 is a class type), where T1 is
4241 // not reference-related to T2, and can be implicitly
4242 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4243 // is reference-compatible with "cv3 T3" 92) (this
4244 // conversion is selected by enumerating the applicable
4245 // conversion functions (13.3.1.6) and choosing the best
4246 // one through overload resolution (13.3)),
4247 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004248 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004249 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004250 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4251 Init, T2, /*AllowRvalues=*/false,
4252 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004253 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004254 }
4255 }
4256
Sebastian Redld92badf2010-06-30 18:13:39 +00004257 // -- Otherwise, the reference shall be an lvalue reference to a
4258 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004259 // shall be an rvalue reference.
Richard Smithce4f6082012-05-24 04:29:20 +00004260 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004261 return ICS;
4262
Douglas Gregorf143cd52011-01-24 16:14:37 +00004263 // -- If the initializer expression
4264 //
4265 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004266 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004267 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4268 (InitCategory.isXValue() ||
4269 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4270 (InitCategory.isLValue() && T2->isFunctionType()))) {
4271 ICS.setStandard();
4272 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004273 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004274 : ObjCConversion? ICK_Compatible_Conversion
4275 : ICK_Identity;
4276 ICS.Standard.Third = ICK_Identity;
4277 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4278 ICS.Standard.setToType(0, T2);
4279 ICS.Standard.setToType(1, T1);
4280 ICS.Standard.setToType(2, T1);
4281 ICS.Standard.ReferenceBinding = true;
4282 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4283 // binding unless we're binding to a class prvalue.
4284 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4285 // allow the use of rvalue references in C++98/03 for the benefit of
4286 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004287 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004288 S.getLangOpts().CPlusPlus11 ||
Richard Smithb94afe12014-07-14 19:54:05 +00004289 !(InitCategory.isPRValue() || T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004290 ICS.Standard.IsLvalueReference = !isRValRef;
4291 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004292 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004293 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004294 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Craig Topperc3ec1492014-05-26 06:22:03 +00004295 ICS.Standard.CopyConstructor = nullptr;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004296 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004297 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004298 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004299
Douglas Gregorf143cd52011-01-24 16:14:37 +00004300 // -- has a class type (i.e., T2 is a class type), where T1 is not
4301 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004302 // an xvalue, class prvalue, or function lvalue of type
4303 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004304 // "cv3 T3",
4305 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004306 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004307 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004308 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004309 // class subobject).
4310 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004311 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004312 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4313 Init, T2, /*AllowRvalues=*/true,
4314 AllowExplicit)) {
4315 // In the second case, if the reference is an rvalue reference
4316 // and the second standard conversion sequence of the
4317 // user-defined conversion sequence includes an lvalue-to-rvalue
4318 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004319 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004320 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4321 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4322
Douglas Gregor95273c32011-01-21 16:36:05 +00004323 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004324 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004325
Richard Smith19172c42014-07-14 02:28:44 +00004326 // A temporary of function type cannot be created; don't even try.
4327 if (T1->isFunctionType())
4328 return ICS;
4329
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004330 // -- Otherwise, a temporary of type "cv1 T1" is created and
4331 // initialized from the initializer expression using the
4332 // rules for a non-reference copy initialization (8.5). The
4333 // reference is then bound to the temporary. If T1 is
4334 // reference-related to T2, cv1 must be the same
4335 // cv-qualification as, or greater cv-qualification than,
4336 // cv2; otherwise, the program is ill-formed.
4337 if (RefRelationship == Sema::Ref_Related) {
4338 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4339 // we would be reference-compatible or reference-compatible with
4340 // added qualification. But that wasn't the case, so the reference
4341 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004342 //
4343 // Note that we only want to check address spaces and cvr-qualifiers here.
4344 // ObjC GC and lifetime qualifiers aren't important.
4345 Qualifiers T1Quals = T1.getQualifiers();
4346 Qualifiers T2Quals = T2.getQualifiers();
4347 T1Quals.removeObjCGCAttr();
4348 T1Quals.removeObjCLifetime();
4349 T2Quals.removeObjCGCAttr();
4350 T2Quals.removeObjCLifetime();
4351 if (!T1Quals.compatiblyIncludes(T2Quals))
4352 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004353 }
4354
4355 // If at least one of the types is a class type, the types are not
4356 // related, and we aren't allowed any user conversions, the
4357 // reference binding fails. This case is important for breaking
4358 // recursion, since TryImplicitConversion below will attempt to
4359 // create a temporary through the use of a copy constructor.
4360 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4361 (T1->isRecordType() || T2->isRecordType()))
4362 return ICS;
4363
Douglas Gregorcba72b12011-01-21 05:18:22 +00004364 // If T1 is reference-related to T2 and the reference is an rvalue
4365 // reference, the initializer expression shall not be an lvalue.
4366 if (RefRelationship >= Sema::Ref_Related &&
4367 isRValRef && Init->Classify(S.Context).isLValue())
4368 return ICS;
4369
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004370 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004371 // When a parameter of reference type is not bound directly to
4372 // an argument expression, the conversion sequence is the one
4373 // required to convert the argument expression to the
4374 // underlying type of the reference according to
4375 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4376 // to copy-initializing a temporary of the underlying type with
4377 // the argument expression. Any difference in top-level
4378 // cv-qualification is subsumed by the initialization itself
4379 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004380 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4381 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004382 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004383 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004384 /*AllowObjCWritebackConversion=*/false,
4385 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004386
4387 // Of course, that's still a reference binding.
4388 if (ICS.isStandard()) {
4389 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004390 ICS.Standard.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004391 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004392 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004393 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004394 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004395 } else if (ICS.isUserDefined()) {
Richard Smith19172c42014-07-14 02:28:44 +00004396 const ReferenceType *LValRefType =
4397 ICS.UserDefined.ConversionFunction->getReturnType()
4398 ->getAs<LValueReferenceType>();
4399
4400 // C++ [over.ics.ref]p3:
4401 // Except for an implicit object parameter, for which see 13.3.1, a
4402 // standard conversion sequence cannot be formed if it requires [...]
4403 // binding an rvalue reference to an lvalue other than a function
4404 // lvalue.
4405 // Note that the function case is not possible here.
4406 if (DeclType->isRValueReferenceType() && LValRefType) {
4407 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4408 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4409 // reference to an rvalue!
4410 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4411 return ICS;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004412 }
Richard Smith19172c42014-07-14 02:28:44 +00004413
Ismail Pazarbasi99afd962014-01-24 10:54:12 +00004414 ICS.UserDefined.Before.setAsIdentityConversion();
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004415 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004416 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
Richard Smith19172c42014-07-14 02:28:44 +00004417 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4418 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004419 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4420 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004421 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004422
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004423 return ICS;
4424}
4425
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004426static ImplicitConversionSequence
4427TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4428 bool SuppressUserConversions,
4429 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004430 bool AllowObjCWritebackConversion,
4431 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004432
4433/// TryListConversion - Try to copy-initialize a value of type ToType from the
4434/// initializer list From.
4435static ImplicitConversionSequence
4436TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4437 bool SuppressUserConversions,
4438 bool InOverloadResolution,
4439 bool AllowObjCWritebackConversion) {
4440 // C++11 [over.ics.list]p1:
4441 // When an argument is an initializer list, it is not an expression and
4442 // special rules apply for converting it to a parameter type.
4443
4444 ImplicitConversionSequence Result;
4445 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4446
Sebastian Redl09edce02012-01-23 22:09:39 +00004447 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004448 // initialized from init lists.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004449 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004450 return Result;
4451
Larisse Voufo19d08672015-01-27 18:47:05 +00004452 // Per DR1467:
4453 // If the parameter type is a class X and the initializer list has a single
4454 // element of type cv U, where U is X or a class derived from X, the
4455 // implicit conversion sequence is the one required to convert the element
4456 // to the parameter type.
4457 //
4458 // Otherwise, if the parameter type is a character array [... ]
4459 // and the initializer list has a single element that is an
4460 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4461 // implicit conversion sequence is the identity conversion.
4462 if (From->getNumInits() == 1) {
4463 if (ToType->isRecordType()) {
4464 QualType InitType = From->getInit(0)->getType();
4465 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4466 S.IsDerivedFrom(InitType, ToType))
4467 return TryCopyInitialization(S, From->getInit(0), ToType,
4468 SuppressUserConversions,
4469 InOverloadResolution,
4470 AllowObjCWritebackConversion);
4471 }
Richard Smith1bbaba82015-01-27 23:23:39 +00004472 // FIXME: Check the other conditions here: array of character type,
4473 // initializer is a string literal.
4474 if (ToType->isArrayType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004475 InitializedEntity Entity =
4476 InitializedEntity::InitializeParameter(S.Context, ToType,
4477 /*Consumed=*/false);
4478 if (S.CanPerformCopyInitialization(Entity, From)) {
4479 Result.setStandard();
4480 Result.Standard.setAsIdentityConversion();
4481 Result.Standard.setFromType(ToType);
4482 Result.Standard.setAllToTypes(ToType);
4483 return Result;
4484 }
4485 }
4486 }
4487
4488 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004489 // C++11 [over.ics.list]p2:
4490 // If the parameter type is std::initializer_list<X> or "array of X" and
4491 // all the elements can be implicitly converted to X, the implicit
4492 // conversion sequence is the worst conversion necessary to convert an
4493 // element of the list to X.
Larisse Voufo19d08672015-01-27 18:47:05 +00004494 //
4495 // C++14 [over.ics.list]p3:
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00004496 // Otherwise, if the parameter type is "array of N X", if the initializer
Larisse Voufo19d08672015-01-27 18:47:05 +00004497 // list has exactly N elements or if it has fewer than N elements and X is
4498 // default-constructible, and if all the elements of the initializer list
4499 // can be implicitly converted to X, the implicit conversion sequence is
4500 // the worst conversion necessary to convert an element of the list to X.
Richard Smith1bbaba82015-01-27 23:23:39 +00004501 //
4502 // FIXME: We're missing a lot of these checks.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004503 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004504 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004505 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004506 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004507 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004508 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004509 if (!X.isNull()) {
4510 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4511 Expr *Init = From->getInit(i);
4512 ImplicitConversionSequence ICS =
4513 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4514 InOverloadResolution,
4515 AllowObjCWritebackConversion);
4516 // If a single element isn't convertible, fail.
4517 if (ICS.isBad()) {
4518 Result = ICS;
4519 break;
4520 }
4521 // Otherwise, look for the worst conversion.
4522 if (Result.isBad() ||
4523 CompareImplicitConversionSequences(S, ICS, Result) ==
4524 ImplicitConversionSequence::Worse)
4525 Result = ICS;
4526 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004527
4528 // For an empty list, we won't have computed any conversion sequence.
4529 // Introduce the identity conversion sequence.
4530 if (From->getNumInits() == 0) {
4531 Result.setStandard();
4532 Result.Standard.setAsIdentityConversion();
4533 Result.Standard.setFromType(ToType);
4534 Result.Standard.setAllToTypes(ToType);
4535 }
4536
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004537 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004538 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004539 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004540
Larisse Voufo19d08672015-01-27 18:47:05 +00004541 // C++14 [over.ics.list]p4:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004542 // C++11 [over.ics.list]p3:
4543 // Otherwise, if the parameter is a non-aggregate class X and overload
4544 // resolution chooses a single best constructor [...] the implicit
4545 // conversion sequence is a user-defined conversion sequence. If multiple
4546 // constructors are viable but none is better than the others, the
4547 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004548 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4549 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004550 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4551 /*AllowExplicit=*/false,
4552 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004553 AllowObjCWritebackConversion,
4554 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004555 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004556
Larisse Voufo19d08672015-01-27 18:47:05 +00004557 // C++14 [over.ics.list]p5:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004558 // C++11 [over.ics.list]p4:
4559 // Otherwise, if the parameter has an aggregate type which can be
4560 // initialized from the initializer list [...] the implicit conversion
4561 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004562 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004563 // Type is an aggregate, argument is an init list. At this point it comes
4564 // down to checking whether the initialization works.
4565 // FIXME: Find out whether this parameter is consumed or not.
4566 InitializedEntity Entity =
4567 InitializedEntity::InitializeParameter(S.Context, ToType,
4568 /*Consumed=*/false);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004569 if (S.CanPerformCopyInitialization(Entity, From)) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004570 Result.setUserDefined();
4571 Result.UserDefined.Before.setAsIdentityConversion();
4572 // Initializer lists don't have a type.
4573 Result.UserDefined.Before.setFromType(QualType());
4574 Result.UserDefined.Before.setAllToTypes(QualType());
4575
4576 Result.UserDefined.After.setAsIdentityConversion();
4577 Result.UserDefined.After.setFromType(ToType);
4578 Result.UserDefined.After.setAllToTypes(ToType);
Craig Topperc3ec1492014-05-26 06:22:03 +00004579 Result.UserDefined.ConversionFunction = nullptr;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004580 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004581 return Result;
4582 }
4583
Larisse Voufo19d08672015-01-27 18:47:05 +00004584 // C++14 [over.ics.list]p6:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004585 // C++11 [over.ics.list]p5:
4586 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004587 if (ToType->isReferenceType()) {
4588 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4589 // mention initializer lists in any way. So we go by what list-
4590 // initialization would do and try to extrapolate from that.
4591
4592 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4593
4594 // If the initializer list has a single element that is reference-related
4595 // to the parameter type, we initialize the reference from that.
4596 if (From->getNumInits() == 1) {
4597 Expr *Init = From->getInit(0);
4598
4599 QualType T2 = Init->getType();
4600
4601 // If the initializer is the address of an overloaded function, try
4602 // to resolve the overloaded function. If all goes well, T2 is the
4603 // type of the resulting function.
4604 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4605 DeclAccessPair Found;
4606 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4607 Init, ToType, false, Found))
4608 T2 = Fn->getType();
4609 }
4610
4611 // Compute some basic properties of the types and the initializer.
4612 bool dummy1 = false;
4613 bool dummy2 = false;
4614 bool dummy3 = false;
4615 Sema::ReferenceCompareResult RefRelationship
4616 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4617 dummy2, dummy3);
4618
Richard Smith4d2bbd72013-09-06 01:22:42 +00004619 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004620 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4621 SuppressUserConversions,
4622 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004623 }
Sebastian Redldf888642011-12-03 14:54:30 +00004624 }
4625
4626 // Otherwise, we bind the reference to a temporary created from the
4627 // initializer list.
4628 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4629 InOverloadResolution,
4630 AllowObjCWritebackConversion);
4631 if (Result.isFailure())
4632 return Result;
4633 assert(!Result.isEllipsis() &&
4634 "Sub-initialization cannot result in ellipsis conversion.");
4635
4636 // Can we even bind to a temporary?
4637 if (ToType->isRValueReferenceType() ||
4638 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4639 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4640 Result.UserDefined.After;
4641 SCS.ReferenceBinding = true;
4642 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4643 SCS.BindsToRvalue = true;
4644 SCS.BindsToFunctionLvalue = false;
4645 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4646 SCS.ObjCLifetimeConversionBinding = false;
4647 } else
4648 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4649 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004650 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004651 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004652
Larisse Voufo19d08672015-01-27 18:47:05 +00004653 // C++14 [over.ics.list]p7:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004654 // C++11 [over.ics.list]p6:
4655 // Otherwise, if the parameter type is not a class:
4656 if (!ToType->isRecordType()) {
Larisse Voufo19d08672015-01-27 18:47:05 +00004657 // - if the initializer list has one element that is not itself an
4658 // initializer list, the implicit conversion sequence is the one
4659 // required to convert the element to the parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004660 unsigned NumInits = From->getNumInits();
Richard Smith1bbaba82015-01-27 23:23:39 +00004661 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004662 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4663 SuppressUserConversions,
4664 InOverloadResolution,
4665 AllowObjCWritebackConversion);
4666 // - if the initializer list has no elements, the implicit conversion
4667 // sequence is the identity conversion.
4668 else if (NumInits == 0) {
4669 Result.setStandard();
4670 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004671 Result.Standard.setFromType(ToType);
4672 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004673 }
4674 return Result;
4675 }
4676
Larisse Voufo19d08672015-01-27 18:47:05 +00004677 // C++14 [over.ics.list]p8:
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004678 // C++11 [over.ics.list]p7:
4679 // In all cases other than those enumerated above, no conversion is possible
4680 return Result;
4681}
4682
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004683/// TryCopyInitialization - Try to copy-initialize a value of type
4684/// ToType from the expression From. Return the implicit conversion
4685/// sequence required to pass this argument, which may be a bad
4686/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004687/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004688/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004689static ImplicitConversionSequence
4690TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004691 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004692 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004693 bool AllowObjCWritebackConversion,
4694 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004695 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4696 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4697 InOverloadResolution,AllowObjCWritebackConversion);
4698
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004699 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004700 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004701 /*FIXME:*/From->getLocStart(),
4702 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004703 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004704
John McCall5c32be02010-08-24 20:38:10 +00004705 return TryImplicitConversion(S, From, ToType,
4706 SuppressUserConversions,
4707 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004708 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004709 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004710 AllowObjCWritebackConversion,
4711 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004712}
4713
Anna Zaks1b068122011-07-28 19:46:48 +00004714static bool TryCopyInitialization(const CanQualType FromQTy,
4715 const CanQualType ToQTy,
4716 Sema &S,
4717 SourceLocation Loc,
4718 ExprValueKind FromVK) {
4719 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4720 ImplicitConversionSequence ICS =
4721 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4722
4723 return !ICS.isBad();
4724}
4725
Douglas Gregor436424c2008-11-18 23:14:02 +00004726/// TryObjectArgumentInitialization - Try to initialize the object
4727/// parameter of the given member function (@c Method) from the
4728/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004729static ImplicitConversionSequence
Richard Smith03c66d32013-01-26 02:07:32 +00004730TryObjectArgumentInitialization(Sema &S, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004731 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004732 CXXMethodDecl *Method,
4733 CXXRecordDecl *ActingContext) {
4734 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004735 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4736 // const volatile object.
4737 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4738 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004739 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004740
4741 // Set up the conversion sequence as a "bad" conversion, to allow us
4742 // to exit early.
4743 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004744
4745 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00004746 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004747 FromType = PT->getPointeeType();
4748
Douglas Gregor02824322011-01-26 19:30:28 +00004749 // When we had a pointer, it's implicitly dereferenced, so we
4750 // better have an lvalue.
4751 assert(FromClassification.isLValue());
4752 }
4753
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004754 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004755
Douglas Gregor02824322011-01-26 19:30:28 +00004756 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004757 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004758 // parameter is
4759 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004760 // - "lvalue reference to cv X" for functions declared without a
4761 // ref-qualifier or with the & ref-qualifier
4762 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004763 // ref-qualifier
4764 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004765 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004766 // cv-qualification on the member function declaration.
4767 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004768 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004769 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004770 // (C++ [over.match.funcs]p5). We perform a simplified version of
4771 // reference binding here, that allows class rvalues to bind to
4772 // non-constant references.
4773
Douglas Gregor02824322011-01-26 19:30:28 +00004774 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004775 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004776 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004777 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004778 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004779 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00004780 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004781 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004782 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004783
4784 // Check that we have either the same type or a derived type. It
4785 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004786 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004787 ImplicitConversionKind SecondKind;
4788 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4789 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004790 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004791 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004792 else {
John McCall65eb8792010-02-25 01:37:24 +00004793 ICS.setBad(BadConversionSequence::unrelated_class,
4794 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004795 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004796 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004797
Douglas Gregor02824322011-01-26 19:30:28 +00004798 // Check the ref-qualifier.
4799 switch (Method->getRefQualifier()) {
4800 case RQ_None:
4801 // Do nothing; we don't care about lvalueness or rvalueness.
4802 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004803
Douglas Gregor02824322011-01-26 19:30:28 +00004804 case RQ_LValue:
4805 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4806 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004807 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004808 ImplicitParamType);
4809 return ICS;
4810 }
4811 break;
4812
4813 case RQ_RValue:
4814 if (!FromClassification.isRValue()) {
4815 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004816 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004817 ImplicitParamType);
4818 return ICS;
4819 }
4820 break;
4821 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004822
Douglas Gregor436424c2008-11-18 23:14:02 +00004823 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004824 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004825 ICS.Standard.setAsIdentityConversion();
4826 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004827 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004828 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004829 ICS.Standard.ReferenceBinding = true;
4830 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004831 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004832 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004833 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4834 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4835 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004836 return ICS;
4837}
4838
4839/// PerformObjectArgumentInitialization - Perform initialization of
4840/// the implicit object parameter for the given Method with the given
4841/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004842ExprResult
4843Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004844 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004845 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004846 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004847 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004848 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004849 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004850
Douglas Gregor02824322011-01-26 19:30:28 +00004851 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004852 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004853 FromRecordType = PT->getPointeeType();
4854 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004855 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004856 } else {
4857 FromRecordType = From->getType();
4858 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004859 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004860 }
4861
John McCall6e9f8f62009-12-03 04:06:58 +00004862 // Note that we always use the true parent context when performing
4863 // the actual argument initialization.
Nico Weberb58e51c2014-11-19 05:21:39 +00004864 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
4865 *this, From->getType(), FromClassification, Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004866 if (ICS.isBad()) {
4867 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4868 Qualifiers FromQs = FromRecordType.getQualifiers();
4869 Qualifiers ToQs = DestType.getQualifiers();
4870 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4871 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004872 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004873 diag::err_member_function_call_bad_cvr)
4874 << Method->getDeclName() << FromRecordType << (CVR - 1)
4875 << From->getSourceRange();
4876 Diag(Method->getLocation(), diag::note_previous_decl)
4877 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004878 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004879 }
4880 }
4881
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004882 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004883 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004884 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004885 }
Mike Stump11289f42009-09-09 15:08:12 +00004886
John Wiegley01296292011-04-08 18:41:53 +00004887 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4888 ExprResult FromRes =
4889 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4890 if (FromRes.isInvalid())
4891 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004892 From = FromRes.get();
John Wiegley01296292011-04-08 18:41:53 +00004893 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004894
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004895 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004896 From = ImpCastExprToType(From, DestType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004897 From->getValueKind()).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004898 return From;
Douglas Gregor436424c2008-11-18 23:14:02 +00004899}
4900
Douglas Gregor5fb53972009-01-14 15:45:31 +00004901/// TryContextuallyConvertToBool - Attempt to contextually convert the
4902/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004903static ImplicitConversionSequence
4904TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00004905 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004906 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004907 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004908 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004909 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004910 /*AllowObjCWritebackConversion=*/false,
4911 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004912}
4913
4914/// PerformContextuallyConvertToBool - Perform a contextual conversion
4915/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004916ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004917 if (checkPlaceholderForOverload(*this, From))
4918 return ExprError();
4919
John McCall5c32be02010-08-24 20:38:10 +00004920 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004921 if (!ICS.isBad())
4922 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004923
Fariborz Jahanian76197412009-11-18 18:26:29 +00004924 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004925 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00004926 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004927 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004928 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004929}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004930
Richard Smithf8379a02012-01-18 23:55:52 +00004931/// Check that the specified conversion is permitted in a converted constant
4932/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4933/// is acceptable.
4934static bool CheckConvertedConstantConversions(Sema &S,
4935 StandardConversionSequence &SCS) {
4936 // Since we know that the target type is an integral or unscoped enumeration
4937 // type, most conversion kinds are impossible. All possible First and Third
4938 // conversions are fine.
4939 switch (SCS.Second) {
4940 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00004941 case ICK_NoReturn_Adjustment:
Richard Smithf8379a02012-01-18 23:55:52 +00004942 case ICK_Integral_Promotion:
Richard Smith410cc892014-11-26 03:26:53 +00004943 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
Richard Smithf8379a02012-01-18 23:55:52 +00004944 return true;
4945
4946 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00004947 // Conversion from an integral or unscoped enumeration type to bool is
Richard Smith410cc892014-11-26 03:26:53 +00004948 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
4949 // conversion, so we allow it in a converted constant expression.
4950 //
4951 // FIXME: Per core issue 1407, we should not allow this, but that breaks
4952 // a lot of popular code. We should at least add a warning for this
4953 // (non-conforming) extension.
Richard Smithca24ed42012-09-13 22:00:12 +00004954 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4955 SCS.getToType(2)->isBooleanType();
4956
Richard Smith410cc892014-11-26 03:26:53 +00004957 case ICK_Pointer_Conversion:
4958 case ICK_Pointer_Member:
4959 // C++1z: null pointer conversions and null member pointer conversions are
4960 // only permitted if the source type is std::nullptr_t.
4961 return SCS.getFromType()->isNullPtrType();
4962
4963 case ICK_Floating_Promotion:
4964 case ICK_Complex_Promotion:
4965 case ICK_Floating_Conversion:
4966 case ICK_Complex_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00004967 case ICK_Floating_Integral:
Richard Smith410cc892014-11-26 03:26:53 +00004968 case ICK_Compatible_Conversion:
4969 case ICK_Derived_To_Base:
4970 case ICK_Vector_Conversion:
4971 case ICK_Vector_Splat:
Richard Smithf8379a02012-01-18 23:55:52 +00004972 case ICK_Complex_Real:
Richard Smith410cc892014-11-26 03:26:53 +00004973 case ICK_Block_Pointer_Conversion:
4974 case ICK_TransparentUnionConversion:
4975 case ICK_Writeback_Conversion:
4976 case ICK_Zero_Event_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00004977 return false;
4978
4979 case ICK_Lvalue_To_Rvalue:
4980 case ICK_Array_To_Pointer:
4981 case ICK_Function_To_Pointer:
Richard Smith410cc892014-11-26 03:26:53 +00004982 llvm_unreachable("found a first conversion kind in Second");
4983
Richard Smithf8379a02012-01-18 23:55:52 +00004984 case ICK_Qualification:
Richard Smith410cc892014-11-26 03:26:53 +00004985 llvm_unreachable("found a third conversion kind in Second");
Richard Smithf8379a02012-01-18 23:55:52 +00004986
4987 case ICK_Num_Conversion_Kinds:
4988 break;
4989 }
4990
4991 llvm_unreachable("unknown conversion kind");
4992}
4993
4994/// CheckConvertedConstantExpression - Check that the expression From is a
4995/// converted constant expression of type T, perform the conversion and produce
4996/// the converted expression, per C++11 [expr.const]p3.
Richard Smith410cc892014-11-26 03:26:53 +00004997static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
4998 QualType T, APValue &Value,
4999 Sema::CCEKind CCE,
5000 bool RequireInt) {
5001 assert(S.getLangOpts().CPlusPlus11 &&
5002 "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00005003
Richard Smith410cc892014-11-26 03:26:53 +00005004 if (checkPlaceholderForOverload(S, From))
Richard Smithf8379a02012-01-18 23:55:52 +00005005 return ExprError();
5006
Richard Smith410cc892014-11-26 03:26:53 +00005007 // C++1z [expr.const]p3:
5008 // A converted constant expression of type T is an expression,
5009 // implicitly converted to type T, where the converted
5010 // expression is a constant expression and the implicit conversion
5011 // sequence contains only [... list of conversions ...].
Richard Smithf8379a02012-01-18 23:55:52 +00005012 ImplicitConversionSequence ICS =
Richard Smith410cc892014-11-26 03:26:53 +00005013 TryCopyInitialization(S, From, T,
Richard Smithf8379a02012-01-18 23:55:52 +00005014 /*SuppressUserConversions=*/false,
Richard Smithf8379a02012-01-18 23:55:52 +00005015 /*InOverloadResolution=*/false,
Richard Smith410cc892014-11-26 03:26:53 +00005016 /*AllowObjcWritebackConversion=*/false,
5017 /*AllowExplicit=*/false);
Craig Topperc3ec1492014-05-26 06:22:03 +00005018 StandardConversionSequence *SCS = nullptr;
Richard Smithf8379a02012-01-18 23:55:52 +00005019 switch (ICS.getKind()) {
5020 case ImplicitConversionSequence::StandardConversion:
Richard Smithf8379a02012-01-18 23:55:52 +00005021 SCS = &ICS.Standard;
5022 break;
5023 case ImplicitConversionSequence::UserDefinedConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005024 // We are converting to a non-class type, so the Before sequence
5025 // must be trivial.
Richard Smithf8379a02012-01-18 23:55:52 +00005026 SCS = &ICS.UserDefined.After;
5027 break;
5028 case ImplicitConversionSequence::AmbiguousConversion:
5029 case ImplicitConversionSequence::BadConversion:
Richard Smith410cc892014-11-26 03:26:53 +00005030 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5031 return S.Diag(From->getLocStart(),
5032 diag::err_typecheck_converted_constant_expression)
5033 << From->getType() << From->getSourceRange() << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005034 return ExprError();
5035
5036 case ImplicitConversionSequence::EllipsisConversion:
5037 llvm_unreachable("ellipsis conversion in converted constant expression");
5038 }
5039
Richard Smith410cc892014-11-26 03:26:53 +00005040 // Check that we would only use permitted conversions.
5041 if (!CheckConvertedConstantConversions(S, *SCS)) {
5042 return S.Diag(From->getLocStart(),
5043 diag::err_typecheck_converted_constant_expression_disallowed)
5044 << From->getType() << From->getSourceRange() << T;
5045 }
5046 // [...] and where the reference binding (if any) binds directly.
5047 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5048 return S.Diag(From->getLocStart(),
5049 diag::err_typecheck_converted_constant_expression_indirect)
5050 << From->getType() << From->getSourceRange() << T;
5051 }
5052
5053 ExprResult Result =
5054 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
Richard Smithf8379a02012-01-18 23:55:52 +00005055 if (Result.isInvalid())
5056 return Result;
5057
5058 // Check for a narrowing implicit conversion.
5059 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005060 QualType PreNarrowingType;
Richard Smith410cc892014-11-26 03:26:53 +00005061 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
Richard Smith5614ca72012-03-23 23:55:39 +00005062 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00005063 case NK_Variable_Narrowing:
5064 // Implicit conversion to a narrower type, and the value is not a constant
5065 // expression. We'll diagnose this in a moment.
5066 case NK_Not_Narrowing:
5067 break;
5068
5069 case NK_Constant_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005070 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005071 << CCE << /*Constant*/1
Richard Smith410cc892014-11-26 03:26:53 +00005072 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005073 break;
5074
5075 case NK_Type_Narrowing:
Richard Smith410cc892014-11-26 03:26:53 +00005076 S.Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005077 << CCE << /*Constant*/0 << From->getType() << T;
5078 break;
5079 }
5080
5081 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005082 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005083 Expr::EvalResult Eval;
5084 Eval.Diag = &Notes;
5085
Richard Smith410cc892014-11-26 03:26:53 +00005086 if ((T->isReferenceType()
5087 ? !Result.get()->EvaluateAsLValue(Eval, S.Context)
5088 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) ||
5089 (RequireInt && !Eval.Val.isInt())) {
Richard Smithf8379a02012-01-18 23:55:52 +00005090 // The expression can't be folded, so we can't keep it at this position in
5091 // the AST.
5092 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005093 } else {
Richard Smith410cc892014-11-26 03:26:53 +00005094 Value = Eval.Val;
Richard Smith911e1422012-01-30 22:27:01 +00005095
5096 if (Notes.empty()) {
5097 // It's a constant expression.
5098 return Result;
5099 }
Richard Smithf8379a02012-01-18 23:55:52 +00005100 }
5101
5102 // It's not a constant expression. Produce an appropriate diagnostic.
5103 if (Notes.size() == 1 &&
5104 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
Richard Smith410cc892014-11-26 03:26:53 +00005105 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
Richard Smithf8379a02012-01-18 23:55:52 +00005106 else {
Richard Smith410cc892014-11-26 03:26:53 +00005107 S.Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005108 << CCE << From->getSourceRange();
5109 for (unsigned I = 0; I < Notes.size(); ++I)
Richard Smith410cc892014-11-26 03:26:53 +00005110 S.Diag(Notes[I].first, Notes[I].second);
Richard Smithf8379a02012-01-18 23:55:52 +00005111 }
Richard Smith410cc892014-11-26 03:26:53 +00005112 return ExprError();
Richard Smithf8379a02012-01-18 23:55:52 +00005113}
5114
Richard Smith410cc892014-11-26 03:26:53 +00005115ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5116 APValue &Value, CCEKind CCE) {
5117 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5118}
5119
5120ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5121 llvm::APSInt &Value,
5122 CCEKind CCE) {
5123 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5124
5125 APValue V;
5126 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5127 if (!R.isInvalid())
5128 Value = V.getInt();
5129 return R;
5130}
5131
5132
John McCallfec112d2011-09-09 06:11:02 +00005133/// dropPointerConversions - If the given standard conversion sequence
5134/// involves any pointer conversions, remove them. This may change
5135/// the result type of the conversion sequence.
5136static void dropPointerConversion(StandardConversionSequence &SCS) {
5137 if (SCS.Second == ICK_Pointer_Conversion) {
5138 SCS.Second = ICK_Identity;
5139 SCS.Third = ICK_Identity;
5140 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5141 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005142}
John McCall5c32be02010-08-24 20:38:10 +00005143
John McCallfec112d2011-09-09 06:11:02 +00005144/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5145/// convert the expression From to an Objective-C pointer type.
5146static ImplicitConversionSequence
5147TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5148 // Do an implicit conversion to 'id'.
5149 QualType Ty = S.Context.getObjCIdType();
5150 ImplicitConversionSequence ICS
5151 = TryImplicitConversion(S, From, Ty,
5152 // FIXME: Are these flags correct?
5153 /*SuppressUserConversions=*/false,
5154 /*AllowExplicit=*/true,
5155 /*InOverloadResolution=*/false,
5156 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005157 /*AllowObjCWritebackConversion=*/false,
5158 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005159
5160 // Strip off any final conversions to 'id'.
5161 switch (ICS.getKind()) {
5162 case ImplicitConversionSequence::BadConversion:
5163 case ImplicitConversionSequence::AmbiguousConversion:
5164 case ImplicitConversionSequence::EllipsisConversion:
5165 break;
5166
5167 case ImplicitConversionSequence::UserDefinedConversion:
5168 dropPointerConversion(ICS.UserDefined.After);
5169 break;
5170
5171 case ImplicitConversionSequence::StandardConversion:
5172 dropPointerConversion(ICS.Standard);
5173 break;
5174 }
5175
5176 return ICS;
5177}
5178
5179/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5180/// conversion of the expression From to an Objective-C pointer type.
5181ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005182 if (checkPlaceholderForOverload(*this, From))
5183 return ExprError();
5184
John McCall8b07ec22010-05-15 11:32:37 +00005185 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005186 ImplicitConversionSequence ICS =
5187 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005188 if (!ICS.isBad())
5189 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005190 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005191}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005192
Richard Smith8dd34252012-02-04 07:07:42 +00005193/// Determine whether the provided type is an integral type, or an enumeration
5194/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005195bool Sema::ICEConvertDiagnoser::match(QualType T) {
5196 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5197 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005198}
5199
Larisse Voufo236bec22013-06-10 06:50:24 +00005200static ExprResult
5201diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5202 Sema::ContextualImplicitConverter &Converter,
5203 QualType T, UnresolvedSetImpl &ViableConversions) {
5204
5205 if (Converter.Suppress)
5206 return ExprError();
5207
5208 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5209 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5210 CXXConversionDecl *Conv =
5211 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5212 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5213 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5214 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005215 return From;
Larisse Voufo236bec22013-06-10 06:50:24 +00005216}
5217
5218static bool
5219diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5220 Sema::ContextualImplicitConverter &Converter,
5221 QualType T, bool HadMultipleCandidates,
5222 UnresolvedSetImpl &ExplicitConversions) {
5223 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5224 DeclAccessPair Found = ExplicitConversions[0];
5225 CXXConversionDecl *Conversion =
5226 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5227
5228 // The user probably meant to invoke the given explicit
5229 // conversion; use it.
5230 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5231 std::string TypeStr;
5232 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5233
5234 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5235 << FixItHint::CreateInsertion(From->getLocStart(),
5236 "static_cast<" + TypeStr + ">(")
5237 << FixItHint::CreateInsertion(
Alp Tokerb6cc5922014-05-03 03:45:55 +00005238 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
Larisse Voufo236bec22013-06-10 06:50:24 +00005239 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5240
5241 // If we aren't in a SFINAE context, build a call to the
5242 // explicit conversion function.
5243 if (SemaRef.isSFINAEContext())
5244 return true;
5245
Craig Topperc3ec1492014-05-26 06:22:03 +00005246 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005247 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5248 HadMultipleCandidates);
5249 if (Result.isInvalid())
5250 return true;
5251 // Record usage of conversion in an implicit cast.
5252 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005253 CK_UserDefinedConversion, Result.get(),
5254 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005255 }
5256 return false;
5257}
5258
5259static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5260 Sema::ContextualImplicitConverter &Converter,
5261 QualType T, bool HadMultipleCandidates,
5262 DeclAccessPair &Found) {
5263 CXXConversionDecl *Conversion =
5264 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005265 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
Larisse Voufo236bec22013-06-10 06:50:24 +00005266
5267 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5268 if (!Converter.SuppressConversion) {
5269 if (SemaRef.isSFINAEContext())
5270 return true;
5271
5272 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5273 << From->getSourceRange();
5274 }
5275
5276 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5277 HadMultipleCandidates);
5278 if (Result.isInvalid())
5279 return true;
5280 // Record usage of conversion in an implicit cast.
5281 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00005282 CK_UserDefinedConversion, Result.get(),
5283 nullptr, Result.get()->getValueKind());
Larisse Voufo236bec22013-06-10 06:50:24 +00005284 return false;
5285}
5286
5287static ExprResult finishContextualImplicitConversion(
5288 Sema &SemaRef, SourceLocation Loc, Expr *From,
5289 Sema::ContextualImplicitConverter &Converter) {
5290 if (!Converter.match(From->getType()) && !Converter.Suppress)
5291 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5292 << From->getSourceRange();
5293
5294 return SemaRef.DefaultLvalueConversion(From);
5295}
5296
5297static void
5298collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5299 UnresolvedSetImpl &ViableConversions,
5300 OverloadCandidateSet &CandidateSet) {
5301 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5302 DeclAccessPair FoundDecl = ViableConversions[I];
5303 NamedDecl *D = FoundDecl.getDecl();
5304 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5305 if (isa<UsingShadowDecl>(D))
5306 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5307
5308 CXXConversionDecl *Conv;
5309 FunctionTemplateDecl *ConvTemplate;
5310 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5311 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5312 else
5313 Conv = cast<CXXConversionDecl>(D);
5314
5315 if (ConvTemplate)
5316 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005317 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5318 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005319 else
5320 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005321 ToType, CandidateSet,
5322 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005323 }
5324}
5325
Richard Smithccc11812013-05-21 19:05:48 +00005326/// \brief Attempt to convert the given expression to a type which is accepted
5327/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005328///
Richard Smithccc11812013-05-21 19:05:48 +00005329/// This routine will attempt to convert an expression of class type to a
5330/// type accepted by the specified converter. In C++11 and before, the class
5331/// must have a single non-explicit conversion function converting to a matching
5332/// type. In C++1y, there can be multiple such conversion functions, but only
5333/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005334///
Douglas Gregor4799d032010-06-30 00:20:43 +00005335/// \param Loc The source location of the construct that requires the
5336/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005337///
James Dennett18348b62012-06-22 08:52:37 +00005338/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005339///
Richard Smithccc11812013-05-21 19:05:48 +00005340/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005341///
Douglas Gregor4799d032010-06-30 00:20:43 +00005342/// \returns The expression, converted to an integral or enumeration type if
5343/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005344ExprResult Sema::PerformContextualImplicitConversion(
5345 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005346 // We can't perform any more checking for type-dependent expressions.
5347 if (From->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005348 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005349
Eli Friedman1da70392012-01-26 00:26:18 +00005350 // Process placeholders immediately.
5351 if (From->hasPlaceholderType()) {
5352 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005353 if (result.isInvalid())
5354 return result;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005355 From = result.get();
Eli Friedman1da70392012-01-26 00:26:18 +00005356 }
5357
Richard Smithccc11812013-05-21 19:05:48 +00005358 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005359 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005360 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005361 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005362
5363 // FIXME: Check for missing '()' if T is a function type?
5364
Richard Smithccc11812013-05-21 19:05:48 +00005365 // We can only perform contextual implicit conversions on objects of class
5366 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005367 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005368 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005369 if (!Converter.Suppress)
5370 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005371 return From;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005372 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005373
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005374 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005375 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005376 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005377 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005378
5379 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5380 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5381
Craig Toppere14c0f82014-03-12 04:55:44 +00005382 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00005383 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005384 }
Richard Smithccc11812013-05-21 19:05:48 +00005385 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005386
5387 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005388 return From;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005389
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005390 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005391 UnresolvedSet<4>
5392 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005393 UnresolvedSet<4> ExplicitConversions;
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005394 const auto &Conversions =
Larisse Voufo236bec22013-06-10 06:50:24 +00005395 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005396
Larisse Voufo236bec22013-06-10 06:50:24 +00005397 bool HadMultipleCandidates =
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005398 (std::distance(Conversions.begin(), Conversions.end()) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005399
Larisse Voufo236bec22013-06-10 06:50:24 +00005400 // To check that there is only one target type, in C++1y:
5401 QualType ToType;
5402 bool HasUniqueTargetType = true;
5403
5404 // Collect explicit or viable (potentially in C++1y) conversions.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00005405 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005406 NamedDecl *D = (*I)->getUnderlyingDecl();
5407 CXXConversionDecl *Conversion;
5408 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5409 if (ConvTemplate) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005410 if (getLangOpts().CPlusPlus14)
Larisse Voufo236bec22013-06-10 06:50:24 +00005411 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5412 else
5413 continue; // C++11 does not consider conversion operator templates(?).
5414 } else
5415 Conversion = cast<CXXConversionDecl>(D);
5416
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005417 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
Larisse Voufo236bec22013-06-10 06:50:24 +00005418 "Conversion operator templates are considered potentially "
5419 "viable in C++1y");
5420
5421 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5422 if (Converter.match(CurToType) || ConvTemplate) {
5423
5424 if (Conversion->isExplicit()) {
5425 // FIXME: For C++1y, do we need this restriction?
5426 // cf. diagnoseNoViableConversion()
5427 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005428 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005429 } else {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005430 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005431 if (ToType.isNull())
5432 ToType = CurToType.getUnqualifiedType();
5433 else if (HasUniqueTargetType &&
5434 (CurToType.getUnqualifiedType() != ToType))
5435 HasUniqueTargetType = false;
5436 }
5437 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005438 }
Richard Smith8dd34252012-02-04 07:07:42 +00005439 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005440 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005441
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005442 if (getLangOpts().CPlusPlus14) {
Larisse Voufo236bec22013-06-10 06:50:24 +00005443 // C++1y [conv]p6:
5444 // ... An expression e of class type E appearing in such a context
5445 // is said to be contextually implicitly converted to a specified
5446 // type T and is well-formed if and only if e can be implicitly
5447 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005448 // for conversion functions whose return type is cv T or reference to
5449 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005450 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005451
Larisse Voufo236bec22013-06-10 06:50:24 +00005452 // If no unique T is found:
5453 if (ToType.isNull()) {
5454 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5455 HadMultipleCandidates,
5456 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005457 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005458 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005459 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005460
Larisse Voufo236bec22013-06-10 06:50:24 +00005461 // If more than one unique Ts are found:
5462 if (!HasUniqueTargetType)
5463 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5464 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005465
Larisse Voufo236bec22013-06-10 06:50:24 +00005466 // If one unique T is found:
5467 // First, build a candidate set from the previously recorded
5468 // potentially viable conversions.
Richard Smith100b24a2014-04-17 01:52:14 +00005469 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
Larisse Voufo236bec22013-06-10 06:50:24 +00005470 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5471 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005472
Larisse Voufo236bec22013-06-10 06:50:24 +00005473 // Then, perform overload resolution over the candidate set.
5474 OverloadCandidateSet::iterator Best;
5475 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5476 case OR_Success: {
5477 // Apply this conversion.
5478 DeclAccessPair Found =
5479 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5480 if (recordConversion(*this, Loc, From, Converter, T,
5481 HadMultipleCandidates, Found))
5482 return ExprError();
5483 break;
5484 }
5485 case OR_Ambiguous:
5486 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5487 ViableConversions);
5488 case OR_No_Viable_Function:
5489 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5490 HadMultipleCandidates,
5491 ExplicitConversions))
5492 return ExprError();
5493 // fall through 'OR_Deleted' case.
5494 case OR_Deleted:
5495 // We'll complain below about a non-integral condition type.
5496 break;
5497 }
5498 } else {
5499 switch (ViableConversions.size()) {
5500 case 0: {
5501 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5502 HadMultipleCandidates,
5503 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005504 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005505
Larisse Voufo236bec22013-06-10 06:50:24 +00005506 // We'll complain below about a non-integral condition type.
5507 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005508 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005509 case 1: {
5510 // Apply this conversion.
5511 DeclAccessPair Found = ViableConversions[0];
5512 if (recordConversion(*this, Loc, From, Converter, T,
5513 HadMultipleCandidates, Found))
5514 return ExprError();
5515 break;
5516 }
5517 default:
5518 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5519 ViableConversions);
5520 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005521 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005522
Larisse Voufo236bec22013-06-10 06:50:24 +00005523 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005524}
5525
Richard Smith100b24a2014-04-17 01:52:14 +00005526/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5527/// an acceptable non-member overloaded operator for a call whose
5528/// arguments have types T1 (and, if non-empty, T2). This routine
5529/// implements the check in C++ [over.match.oper]p3b2 concerning
5530/// enumeration types.
5531static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5532 FunctionDecl *Fn,
5533 ArrayRef<Expr *> Args) {
5534 QualType T1 = Args[0]->getType();
5535 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5536
5537 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5538 return true;
5539
5540 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5541 return true;
5542
5543 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5544 if (Proto->getNumParams() < 1)
5545 return false;
5546
5547 if (T1->isEnumeralType()) {
5548 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5549 if (Context.hasSameUnqualifiedType(T1, ArgType))
5550 return true;
5551 }
5552
5553 if (Proto->getNumParams() < 2)
5554 return false;
5555
5556 if (!T2.isNull() && T2->isEnumeralType()) {
5557 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5558 if (Context.hasSameUnqualifiedType(T2, ArgType))
5559 return true;
5560 }
5561
5562 return false;
5563}
5564
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005565/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005566/// candidate functions, using the given function call arguments. If
5567/// @p SuppressUserConversions, then don't allow user-defined
5568/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005569///
James Dennett2a4d13c2012-06-15 07:13:21 +00005570/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005571/// based on an incomplete set of function arguments. This feature is used by
5572/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005573void
5574Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005575 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005576 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005577 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005578 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005579 bool PartialOverloading,
5580 bool AllowExplicit) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005581 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005582 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005583 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005584 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005585 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005586
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005587 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005588 if (!isa<CXXConstructorDecl>(Method)) {
5589 // If we get here, it's because we're calling a member function
5590 // that is named without a member access expression (e.g.,
5591 // "this->f") that was either written explicitly or created
5592 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005593 // function, e.g., X::f(). We use an empty type for the implied
5594 // object argument (C++ [over.call.func]p3), and the acting context
5595 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005596 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005597 QualType(), Expr::Classification::makeSimpleLValue(),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005598 Args, CandidateSet, SuppressUserConversions,
5599 PartialOverloading);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005600 return;
5601 }
5602 // We treat a constructor like a non-member function, since its object
5603 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005604 }
5605
Douglas Gregorff7028a2009-11-13 23:59:09 +00005606 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005607 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005608
Richard Smith100b24a2014-04-17 01:52:14 +00005609 // C++ [over.match.oper]p3:
5610 // if no operand has a class type, only those non-member functions in the
5611 // lookup set that have a first parameter of type T1 or "reference to
5612 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5613 // is a right operand) a second parameter of type T2 or "reference to
5614 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5615 // candidate functions.
5616 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5617 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5618 return;
5619
Richard Smith8b86f2d2013-11-04 01:48:18 +00005620 // C++11 [class.copy]p11: [DR1402]
5621 // A defaulted move constructor that is defined as deleted is ignored by
5622 // overload resolution.
5623 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5624 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5625 Constructor->isMoveConstructor())
5626 return;
5627
Douglas Gregor27381f32009-11-23 12:27:39 +00005628 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005629 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005630
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005631 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005632 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005633 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005634 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005635 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005636 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005637 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005638 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005639
John McCall578a1f82014-12-14 01:46:53 +00005640 if (Constructor) {
5641 // C++ [class.copy]p3:
5642 // A member function template is never instantiated to perform the copy
5643 // of a class object to an object of its class type.
5644 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5645 if (Args.size() == 1 &&
5646 Constructor->isSpecializationCopyingObject() &&
5647 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5648 IsDerivedFrom(Args[0]->getType(), ClassType))) {
5649 Candidate.Viable = false;
5650 Candidate.FailureKind = ovl_fail_illegal_constructor;
5651 return;
5652 }
5653 }
5654
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005655 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005656
5657 // (C++ 13.3.2p2): A candidate function having fewer than m
5658 // parameters is viable only if it has an ellipsis in its parameter
5659 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005660 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005661 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005662 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005663 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005664 return;
5665 }
5666
5667 // (C++ 13.3.2p2): A candidate function having more than m parameters
5668 // is viable only if the (m+1)st parameter has a default argument
5669 // (8.3.6). For the purposes of overload resolution, the
5670 // parameter list is truncated on the right, so that there are
5671 // exactly m parameters.
5672 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005673 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005674 // Not enough arguments.
5675 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005676 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005677 return;
5678 }
5679
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005680 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005681 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005682 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +00005683 // Skip the check for callers that are implicit members, because in this
5684 // case we may not yet know what the member's target is; the target is
5685 // inferred for the member automatically, based on the bases and fields of
5686 // the class.
5687 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005688 Candidate.Viable = false;
5689 Candidate.FailureKind = ovl_fail_bad_target;
5690 return;
5691 }
5692
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005693 // Determine the implicit conversion sequences for each of the
5694 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005695 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005696 if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005697 // (C++ 13.3.2p3): for F to be a viable function, there shall
5698 // exist for each argument an implicit conversion sequence
5699 // (13.3.3.1) that converts that argument to the corresponding
5700 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005701 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005702 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005703 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005704 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005705 /*InOverloadResolution=*/true,
5706 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005707 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005708 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005709 if (Candidate.Conversions[ArgIdx].isBad()) {
5710 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005711 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005712 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005713 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005714 } else {
5715 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5716 // argument for which there is no corresponding parameter is
5717 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005718 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005719 }
5720 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005721
5722 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5723 Candidate.Viable = false;
5724 Candidate.FailureKind = ovl_fail_enable_if;
5725 Candidate.DeductionFailure.Data = FailedAttr;
5726 return;
5727 }
5728}
5729
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005730ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args,
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00005731 bool IsInstance) {
5732 SmallVector<ObjCMethodDecl*, 4> Methods;
5733 if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance))
5734 return nullptr;
5735
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005736 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5737 bool Match = true;
5738 ObjCMethodDecl *Method = Methods[b];
5739 unsigned NumNamedArgs = Sel.getNumArgs();
5740 // Method might have more arguments than selector indicates. This is due
5741 // to addition of c-style arguments in method.
5742 if (Method->param_size() > NumNamedArgs)
5743 NumNamedArgs = Method->param_size();
5744 if (Args.size() < NumNamedArgs)
5745 continue;
5746
5747 for (unsigned i = 0; i < NumNamedArgs; i++) {
5748 // We can't do any type-checking on a type-dependent argument.
5749 if (Args[i]->isTypeDependent()) {
5750 Match = false;
5751 break;
5752 }
5753
5754 ParmVarDecl *param = Method->parameters()[i];
5755 Expr *argExpr = Args[i];
5756 assert(argExpr && "SelectBestMethod(): missing expression");
5757
5758 // Strip the unbridged-cast placeholder expression off unless it's
5759 // a consumed argument.
5760 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
5761 !param->hasAttr<CFConsumedAttr>())
5762 argExpr = stripARCUnbridgedCast(argExpr);
5763
5764 // If the parameter is __unknown_anytype, move on to the next method.
5765 if (param->getType() == Context.UnknownAnyTy) {
5766 Match = false;
5767 break;
5768 }
5769
5770 ImplicitConversionSequence ConversionState
5771 = TryCopyInitialization(*this, argExpr, param->getType(),
5772 /*SuppressUserConversions*/false,
5773 /*InOverloadResolution=*/true,
5774 /*AllowObjCWritebackConversion=*/
5775 getLangOpts().ObjCAutoRefCount,
5776 /*AllowExplicit*/false);
5777 if (ConversionState.isBad()) {
5778 Match = false;
5779 break;
5780 }
5781 }
5782 // Promote additional arguments to variadic methods.
5783 if (Match && Method->isVariadic()) {
5784 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
5785 if (Args[i]->isTypeDependent()) {
5786 Match = false;
5787 break;
5788 }
5789 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
5790 nullptr);
5791 if (Arg.isInvalid()) {
5792 Match = false;
5793 break;
5794 }
5795 }
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005796 } else {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005797 // Check for extra arguments to non-variadic methods.
5798 if (Args.size() != NumNamedArgs)
5799 Match = false;
Fariborz Jahanian180d76b2014-08-27 16:38:47 +00005800 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
5801 // Special case when selectors have no argument. In this case, select
5802 // one with the most general result type of 'id'.
5803 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
5804 QualType ReturnT = Methods[b]->getReturnType();
5805 if (ReturnT->isObjCIdType())
5806 return Methods[b];
5807 }
5808 }
5809 }
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00005810
5811 if (Match)
5812 return Method;
5813 }
5814 return nullptr;
5815}
5816
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005817static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); }
5818
5819EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5820 bool MissingImplicitThis) {
5821 // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but
5822 // we need to find the first failing one.
5823 if (!Function->hasAttrs())
Craig Topperc3ec1492014-05-26 06:22:03 +00005824 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005825 AttrVec Attrs = Function->getAttrs();
5826 AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(),
5827 IsNotEnableIfAttr);
5828 if (Attrs.begin() == E)
Craig Topperc3ec1492014-05-26 06:22:03 +00005829 return nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005830 std::reverse(Attrs.begin(), E);
5831
5832 SFINAETrap Trap(*this);
5833
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005834 SmallVector<Expr *, 16> ConvertedArgs;
5835 bool InitializationFailed = false;
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005836 bool ContainsValueDependentExpr = false;
Nick Lewyckye283c552015-08-25 22:33:16 +00005837
5838 // Convert the arguments.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005839 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5840 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
Nick Lewyckyb8336b72014-02-28 05:26:13 +00005841 !cast<CXXMethodDecl>(Function)->isStatic() &&
5842 !isa<CXXConstructorDecl>(Function)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005843 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5844 ExprResult R =
Craig Topperc3ec1492014-05-26 06:22:03 +00005845 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005846 Method, Method);
5847 if (R.isInvalid()) {
5848 InitializationFailed = true;
5849 break;
5850 }
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005851 ContainsValueDependentExpr |= R.get()->isValueDependent();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005852 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005853 } else {
5854 ExprResult R =
5855 PerformCopyInitialization(InitializedEntity::InitializeParameter(
5856 Context,
5857 Function->getParamDecl(i)),
5858 SourceLocation(),
5859 Args[i]);
5860 if (R.isInvalid()) {
5861 InitializationFailed = true;
5862 break;
5863 }
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005864 ContainsValueDependentExpr |= R.get()->isValueDependent();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005865 ConvertedArgs.push_back(R.get());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005866 }
5867 }
5868
5869 if (InitializationFailed || Trap.hasErrorOccurred())
5870 return cast<EnableIfAttr>(Attrs[0]);
5871
Nick Lewyckye283c552015-08-25 22:33:16 +00005872 // Push default arguments if needed.
5873 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
5874 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
5875 ParmVarDecl *P = Function->getParamDecl(i);
5876 ExprResult R = PerformCopyInitialization(
5877 InitializedEntity::InitializeParameter(Context,
5878 Function->getParamDecl(i)),
5879 SourceLocation(),
5880 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg()
5881 : P->getDefaultArg());
5882 if (R.isInvalid()) {
5883 InitializationFailed = true;
5884 break;
5885 }
5886 ContainsValueDependentExpr |= R.get()->isValueDependent();
5887 ConvertedArgs.push_back(R.get());
5888 }
5889
5890 if (InitializationFailed || Trap.hasErrorOccurred())
5891 return cast<EnableIfAttr>(Attrs[0]);
5892 }
5893
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005894 for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) {
5895 APValue Result;
5896 EnableIfAttr *EIA = cast<EnableIfAttr>(*I);
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005897 if (EIA->getCond()->isValueDependent()) {
5898 // Don't even try now, we'll examine it after instantiation.
5899 continue;
5900 }
5901
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005902 if (!EIA->getCond()->EvaluateWithSubstitution(
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00005903 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) {
5904 if (!ContainsValueDependentExpr)
5905 return EIA;
5906 } else if (!Result.isInt() || !Result.getInt().getBoolValue()) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005907 return EIA;
5908 }
5909 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005910 return nullptr;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005911}
5912
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005913/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00005914/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00005915void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005916 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005917 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005918 TemplateArgumentListInfo *ExplicitTemplateArgs,
Richard Smithbcc22fc2012-03-09 08:00:36 +00005919 bool SuppressUserConversions,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005920 bool PartialOverloading) {
John McCall4c4c1df2010-01-26 03:27:55 +00005921 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00005922 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5923 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005924 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005925 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005926 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00005927 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005928 Args.slice(1), CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005929 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005930 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005931 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005932 SuppressUserConversions, PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005933 } else {
John McCalla0296f72010-03-19 07:35:19 +00005934 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005935 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5936 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005937 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005938 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005939 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005940 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005941 Args[0]->Classify(Context), Args.slice(1),
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005942 CandidateSet, SuppressUserConversions,
5943 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005944 else
John McCalla0296f72010-03-19 07:35:19 +00005945 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005946 ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005947 CandidateSet, SuppressUserConversions,
5948 PartialOverloading);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005949 }
Douglas Gregor15448f82009-06-27 21:05:07 +00005950 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005951}
5952
John McCallf0f1cf02009-11-17 07:50:12 +00005953/// AddMethodCandidate - Adds a named decl (which is some kind of
5954/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00005955void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005956 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005957 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005958 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00005959 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005960 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00005961 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00005962 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00005963
5964 if (isa<UsingShadowDecl>(Decl))
5965 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005966
John McCallf0f1cf02009-11-17 07:50:12 +00005967 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5968 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5969 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00005970 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
Craig Topperc3ec1492014-05-26 06:22:03 +00005971 /*ExplicitArgs*/ nullptr,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005972 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005973 Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005974 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005975 } else {
John McCalla0296f72010-03-19 07:35:19 +00005976 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005977 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005978 Args,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005979 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005980 }
5981}
5982
Douglas Gregor436424c2008-11-18 23:14:02 +00005983/// AddMethodCandidate - Adds the given C++ member function to the set
5984/// of candidate functions, using the given function call arguments
5985/// and the object argument (@c Object). For example, in a call
5986/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5987/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5988/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00005989/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00005990void
John McCalla0296f72010-03-19 07:35:19 +00005991Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00005992 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005993 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005994 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005995 OverloadCandidateSet &CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00005996 bool SuppressUserConversions,
5997 bool PartialOverloading) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005998 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005999 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00006000 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00006001 assert(!isa<CXXConstructorDecl>(Method) &&
6002 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00006003
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006004 if (!CandidateSet.isNewCandidate(Method))
6005 return;
6006
Richard Smith8b86f2d2013-11-04 01:48:18 +00006007 // C++11 [class.copy]p23: [DR1402]
6008 // A defaulted move assignment operator that is defined as deleted is
6009 // ignored by overload resolution.
6010 if (Method->isDefaulted() && Method->isDeleted() &&
6011 Method->isMoveAssignmentOperator())
6012 return;
6013
Douglas Gregor27381f32009-11-23 12:27:39 +00006014 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006015 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006016
Douglas Gregor436424c2008-11-18 23:14:02 +00006017 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006018 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006019 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00006020 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006021 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006022 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006023 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00006024
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006025 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00006026
6027 // (C++ 13.3.2p2): A candidate function having fewer than m
6028 // parameters is viable only if it has an ellipsis in its parameter
6029 // list (8.3.5).
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006030 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6031 !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006032 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006033 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006034 return;
6035 }
6036
6037 // (C++ 13.3.2p2): A candidate function having more than m parameters
6038 // is viable only if the (m+1)st parameter has a default argument
6039 // (8.3.6). For the purposes of overload resolution, the
6040 // parameter list is truncated on the right, so that there are
6041 // exactly m parameters.
6042 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006043 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006044 // Not enough arguments.
6045 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006046 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00006047 return;
6048 }
6049
6050 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00006051
John McCall6e9f8f62009-12-03 04:06:58 +00006052 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006053 // The implicit object argument is ignored.
6054 Candidate.IgnoreObjectArgument = true;
6055 else {
6056 // Determine the implicit conversion sequence for the object
6057 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00006058 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00006059 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
6060 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006061 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006062 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006063 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006064 return;
6065 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006066 }
6067
Eli Bendersky291a57e2014-09-25 23:59:08 +00006068 // (CUDA B.1): Check for invalid calls between targets.
6069 if (getLangOpts().CUDA)
6070 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6071 if (CheckCUDATarget(Caller, Method)) {
6072 Candidate.Viable = false;
6073 Candidate.FailureKind = ovl_fail_bad_target;
6074 return;
6075 }
6076
Douglas Gregor436424c2008-11-18 23:14:02 +00006077 // Determine the implicit conversion sequences for each of the
6078 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006079 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006080 if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006081 // (C++ 13.3.2p3): for F to be a viable function, there shall
6082 // exist for each argument an implicit conversion sequence
6083 // (13.3.3.1) that converts that argument to the corresponding
6084 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006085 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006086 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006087 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006088 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00006089 /*InOverloadResolution=*/true,
6090 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006091 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006092 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006093 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006094 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006095 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00006096 }
6097 } else {
6098 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6099 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006100 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006101 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00006102 }
6103 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006104
6105 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6106 Candidate.Viable = false;
6107 Candidate.FailureKind = ovl_fail_enable_if;
6108 Candidate.DeductionFailure.Data = FailedAttr;
6109 return;
6110 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006111}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006112
Douglas Gregor97628d62009-08-21 00:16:32 +00006113/// \brief Add a C++ member function template as a candidate to the candidate
6114/// set, using template argument deduction to produce an appropriate member
6115/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006116void
Douglas Gregor97628d62009-08-21 00:16:32 +00006117Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00006118 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006119 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006120 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006121 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00006122 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006123 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00006124 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006125 bool SuppressUserConversions,
6126 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006127 if (!CandidateSet.isNewCandidate(MethodTmpl))
6128 return;
6129
Douglas Gregor97628d62009-08-21 00:16:32 +00006130 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006131 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00006132 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006133 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00006134 // candidate functions in the usual way.113) A given name can refer to one
6135 // or more function templates and also to a set of overloaded non-template
6136 // functions. In such a case, the candidate functions generated from each
6137 // function template are combined with the set of non-template candidate
6138 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006139 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006140 FunctionDecl *Specialization = nullptr;
Douglas Gregor97628d62009-08-21 00:16:32 +00006141 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006142 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006143 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006144 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006145 Candidate.FoundDecl = FoundDecl;
6146 Candidate.Function = MethodTmpl->getTemplatedDecl();
6147 Candidate.Viable = false;
6148 Candidate.FailureKind = ovl_fail_bad_deduction;
6149 Candidate.IsSurrogate = false;
6150 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006151 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006152 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006153 Info);
6154 return;
6155 }
Mike Stump11289f42009-09-09 15:08:12 +00006156
Douglas Gregor97628d62009-08-21 00:16:32 +00006157 // Add the function template specialization produced by template argument
6158 // deduction as a candidate.
6159 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00006160 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00006161 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00006162 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006163 ActingContext, ObjectType, ObjectClassification, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006164 CandidateSet, SuppressUserConversions, PartialOverloading);
Douglas Gregor97628d62009-08-21 00:16:32 +00006165}
6166
Douglas Gregor05155d82009-08-21 23:19:43 +00006167/// \brief Add a C++ function template specialization as a candidate
6168/// in the candidate set, using template argument deduction to produce
6169/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00006170void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006171Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006172 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006173 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006174 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006175 OverloadCandidateSet& CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006176 bool SuppressUserConversions,
6177 bool PartialOverloading) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006178 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6179 return;
6180
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006181 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00006182 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006183 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00006184 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006185 // candidate functions in the usual way.113) A given name can refer to one
6186 // or more function templates and also to a set of overloaded non-template
6187 // functions. In such a case, the candidate functions generated from each
6188 // function template are combined with the set of non-template candidate
6189 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00006190 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006191 FunctionDecl *Specialization = nullptr;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006192 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006193 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006194 Specialization, Info, PartialOverloading)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006195 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00006196 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00006197 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6198 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006199 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00006200 Candidate.IsSurrogate = false;
6201 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006202 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006203 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006204 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006205 return;
6206 }
Mike Stump11289f42009-09-09 15:08:12 +00006207
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006208 // Add the function template specialization produced by template argument
6209 // deduction as a candidate.
6210 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006211 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00006212 SuppressUserConversions, PartialOverloading);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00006213}
Mike Stump11289f42009-09-09 15:08:12 +00006214
Douglas Gregor4b60a152013-11-07 22:34:54 +00006215/// Determine whether this is an allowable conversion from the result
6216/// of an explicit conversion operator to the expected type, per C++
6217/// [over.match.conv]p1 and [over.match.ref]p1.
6218///
6219/// \param ConvType The return type of the conversion function.
6220///
6221/// \param ToType The type we are converting to.
6222///
6223/// \param AllowObjCPointerConversion Allow a conversion from one
6224/// Objective-C pointer to another.
6225///
6226/// \returns true if the conversion is allowable, false otherwise.
6227static bool isAllowableExplicitConversion(Sema &S,
6228 QualType ConvType, QualType ToType,
6229 bool AllowObjCPointerConversion) {
6230 QualType ToNonRefType = ToType.getNonReferenceType();
6231
6232 // Easy case: the types are the same.
6233 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6234 return true;
6235
6236 // Allow qualification conversions.
6237 bool ObjCLifetimeConversion;
6238 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6239 ObjCLifetimeConversion))
6240 return true;
6241
6242 // If we're not allowed to consider Objective-C pointer conversions,
6243 // we're done.
6244 if (!AllowObjCPointerConversion)
6245 return false;
6246
6247 // Is this an Objective-C pointer conversion?
6248 bool IncompatibleObjC = false;
6249 QualType ConvertedType;
6250 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6251 IncompatibleObjC);
6252}
6253
Douglas Gregora1f013e2008-11-07 22:36:19 +00006254/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006255/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006256/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006257/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006258/// (which may or may not be the same type as the type that the
6259/// conversion function produces).
6260void
6261Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006262 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006263 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006264 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006265 OverloadCandidateSet& CandidateSet,
6266 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006267 assert(!Conversion->getDescribedFunctionTemplate() &&
6268 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006269 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006270 if (!CandidateSet.isNewCandidate(Conversion))
6271 return;
6272
Richard Smith2a7d4812013-05-04 07:00:32 +00006273 // If the conversion function has an undeduced return type, trigger its
6274 // deduction now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00006275 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
Richard Smith2a7d4812013-05-04 07:00:32 +00006276 if (DeduceReturnType(Conversion, From->getExprLoc()))
6277 return;
6278 ConvType = Conversion->getConversionType().getNonReferenceType();
6279 }
6280
Richard Smith089c3162013-09-21 21:55:46 +00006281 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6282 // operator is only a candidate if its return type is the target type or
6283 // can be converted to the target type with a qualification conversion.
Douglas Gregor4b60a152013-11-07 22:34:54 +00006284 if (Conversion->isExplicit() &&
6285 !isAllowableExplicitConversion(*this, ConvType, ToType,
6286 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006287 return;
6288
Douglas Gregor27381f32009-11-23 12:27:39 +00006289 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006290 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006291
Douglas Gregora1f013e2008-11-07 22:36:19 +00006292 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006293 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006294 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006295 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006296 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006297 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006298 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006299 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006300 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006301 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006302 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006303
Douglas Gregor6affc782010-08-19 15:37:02 +00006304 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006305 // For conversion functions, the function is considered to be a member of
6306 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006307 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006308 //
6309 // Determine the implicit conversion sequence for the implicit
6310 // object parameter.
6311 QualType ImplicitParamType = From->getType();
6312 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6313 ImplicitParamType = FromPtrType->getPointeeType();
6314 CXXRecordDecl *ConversionContext
6315 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006316
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006317 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006318 = TryObjectArgumentInitialization(*this, From->getType(),
6319 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00006320 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006321
John McCall0d1da222010-01-12 00:44:57 +00006322 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006323 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006324 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006325 return;
6326 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006327
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006328 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006329 // derived to base as such conversions are given Conversion Rank. They only
6330 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6331 QualType FromCanon
6332 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6333 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6334 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
6335 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006336 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006337 return;
6338 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006339
Douglas Gregora1f013e2008-11-07 22:36:19 +00006340 // To determine what the conversion from the result of calling the
6341 // conversion function to the type we're eventually trying to
6342 // convert to (ToType), we need to synthesize a call to the
6343 // conversion function and attempt copy initialization from it. This
6344 // makes sure that we get the right semantics with respect to
6345 // lvalues/rvalues and the type. Fortunately, we can allocate this
6346 // call on the stack and we don't need its arguments to be
6347 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006348 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006349 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006350 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6351 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006352 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006353 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006354
Richard Smith48d24642011-07-13 22:53:21 +00006355 QualType ConversionType = Conversion->getConversionType();
6356 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006357 Candidate.Viable = false;
6358 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6359 return;
6360 }
6361
Richard Smith48d24642011-07-13 22:53:21 +00006362 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006363
Mike Stump11289f42009-09-09 15:08:12 +00006364 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006365 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6366 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006367 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006368 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006369 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006370 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006371 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006372 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006373 /*InOverloadResolution=*/false,
6374 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006375
John McCall0d1da222010-01-12 00:44:57 +00006376 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006377 case ImplicitConversionSequence::StandardConversion:
6378 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006379
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006380 // C++ [over.ics.user]p3:
6381 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006382 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006383 // shall have exact match rank.
6384 if (Conversion->getPrimaryTemplate() &&
6385 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6386 Candidate.Viable = false;
6387 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006388 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006389 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006390
Douglas Gregorcba72b12011-01-21 05:18:22 +00006391 // C++0x [dcl.init.ref]p5:
6392 // In the second case, if the reference is an rvalue reference and
6393 // the second standard conversion sequence of the user-defined
6394 // conversion sequence includes an lvalue-to-rvalue conversion, the
6395 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006396 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006397 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6398 Candidate.Viable = false;
6399 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006400 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006401 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006402 break;
6403
6404 case ImplicitConversionSequence::BadConversion:
6405 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006406 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006407 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006408
6409 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006410 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006411 "Can only end up with a standard conversion sequence or failure");
6412 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006413
Craig Topper5fc8fc22014-08-27 06:28:36 +00006414 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006415 Candidate.Viable = false;
6416 Candidate.FailureKind = ovl_fail_enable_if;
6417 Candidate.DeductionFailure.Data = FailedAttr;
6418 return;
6419 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006420}
6421
Douglas Gregor05155d82009-08-21 23:19:43 +00006422/// \brief Adds a conversion function template specialization
6423/// candidate to the overload set, using template argument deduction
6424/// to deduce the template arguments of the conversion function
6425/// template from the type that we are converting to (C++
6426/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006427void
Douglas Gregor05155d82009-08-21 23:19:43 +00006428Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006429 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006430 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00006431 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006432 OverloadCandidateSet &CandidateSet,
6433 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006434 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6435 "Only conversion function templates permitted here");
6436
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006437 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6438 return;
6439
Craig Toppere6706e42012-09-19 02:26:47 +00006440 TemplateDeductionInfo Info(CandidateSet.getLocation());
Craig Topperc3ec1492014-05-26 06:22:03 +00006441 CXXConversionDecl *Specialization = nullptr;
Douglas Gregor05155d82009-08-21 23:19:43 +00006442 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006443 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006444 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006445 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006446 Candidate.FoundDecl = FoundDecl;
6447 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6448 Candidate.Viable = false;
6449 Candidate.FailureKind = ovl_fail_bad_deduction;
6450 Candidate.IsSurrogate = false;
6451 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006452 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006453 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006454 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006455 return;
6456 }
Mike Stump11289f42009-09-09 15:08:12 +00006457
Douglas Gregor05155d82009-08-21 23:19:43 +00006458 // Add the conversion function template specialization produced by
6459 // template argument deduction as a candidate.
6460 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00006461 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006462 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor05155d82009-08-21 23:19:43 +00006463}
6464
Douglas Gregorab7897a2008-11-19 22:57:39 +00006465/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6466/// converts the given @c Object to a function pointer via the
6467/// conversion function @c Conversion, and then attempts to call it
6468/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6469/// the type of function that we'll eventually be calling.
6470void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006471 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006472 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006473 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00006474 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006475 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00006476 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006477 if (!CandidateSet.isNewCandidate(Conversion))
6478 return;
6479
Douglas Gregor27381f32009-11-23 12:27:39 +00006480 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006481 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006482
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006483 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006484 Candidate.FoundDecl = FoundDecl;
Craig Topperc3ec1492014-05-26 06:22:03 +00006485 Candidate.Function = nullptr;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006486 Candidate.Surrogate = Conversion;
6487 Candidate.Viable = true;
6488 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006489 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006490 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006491
6492 // Determine the implicit conversion sequence for the implicit
6493 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00006494 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006495 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00006496 Object->Classify(Context),
6497 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006498 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006499 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006500 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00006501 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006502 return;
6503 }
6504
6505 // The first conversion is actually a user-defined conversion whose
6506 // first conversion is ObjectInit's standard conversion (which is
6507 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00006508 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006509 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00006510 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006511 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006512 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00006513 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00006514 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00006515 = Candidate.Conversions[0].UserDefined.Before;
6516 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6517
Mike Stump11289f42009-09-09 15:08:12 +00006518 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006519 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006520
6521 // (C++ 13.3.2p2): A candidate function having fewer than m
6522 // parameters is viable only if it has an ellipsis in its parameter
6523 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006524 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006525 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006526 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006527 return;
6528 }
6529
6530 // Function types don't have any default arguments, so just check if
6531 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006532 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006533 // Not enough arguments.
6534 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006535 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006536 return;
6537 }
6538
6539 // Determine the implicit conversion sequences for each of the
6540 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00006541 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006542 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006543 // (C++ 13.3.2p3): for F to be a viable function, there shall
6544 // exist for each argument an implicit conversion sequence
6545 // (13.3.3.1) that converts that argument to the corresponding
6546 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006547 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006548 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006549 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006550 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00006551 /*InOverloadResolution=*/false,
6552 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006553 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006554 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006555 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006556 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006557 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006558 }
6559 } else {
6560 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6561 // argument for which there is no corresponding parameter is
6562 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006563 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006564 }
6565 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006566
Craig Topper5fc8fc22014-08-27 06:28:36 +00006567 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006568 Candidate.Viable = false;
6569 Candidate.FailureKind = ovl_fail_enable_if;
6570 Candidate.DeductionFailure.Data = FailedAttr;
6571 return;
6572 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00006573}
6574
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006575/// \brief Add overload candidates for overloaded operators that are
6576/// member functions.
6577///
6578/// Add the overloaded operator candidates that are member functions
6579/// for the operator Op that was used in an operator expression such
6580/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6581/// CandidateSet will store the added overload candidates. (C++
6582/// [over.match.oper]).
6583void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6584 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00006585 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006586 OverloadCandidateSet& CandidateSet,
6587 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006588 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6589
6590 // C++ [over.match.oper]p3:
6591 // For a unary operator @ with an operand of a type whose
6592 // cv-unqualified version is T1, and for a binary operator @ with
6593 // a left operand of a type whose cv-unqualified version is T1 and
6594 // a right operand of a type whose cv-unqualified version is T2,
6595 // three sets of candidate functions, designated member
6596 // candidates, non-member candidates and built-in candidates, are
6597 // constructed as follows:
6598 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00006599
Richard Smith0feaf0c2013-04-20 12:41:22 +00006600 // -- If T1 is a complete class type or a class currently being
6601 // defined, the set of member candidates is the result of the
6602 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6603 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006604 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00006605 // Complete the type if it can be completed.
6606 RequireCompleteType(OpLoc, T1, 0);
6607 // If the type is neither complete nor being defined, bail out now.
6608 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006609 return;
Mike Stump11289f42009-09-09 15:08:12 +00006610
John McCall27b18f82009-11-17 02:14:36 +00006611 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6612 LookupQualifiedName(Operators, T1Rec->getDecl());
6613 Operators.suppressDiagnostics();
6614
Mike Stump11289f42009-09-09 15:08:12 +00006615 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006616 OperEnd = Operators.end();
6617 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00006618 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00006619 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola51629df2013-04-29 19:29:25 +00006620 Args[0]->Classify(Context),
Richard Smithe54c3072013-05-05 15:51:06 +00006621 Args.slice(1),
Douglas Gregor02824322011-01-26 19:30:28 +00006622 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006623 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00006624 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006625}
6626
Douglas Gregora11693b2008-11-12 17:17:38 +00006627/// AddBuiltinCandidate - Add a candidate for a built-in
6628/// operator. ResultTy and ParamTys are the result and parameter types
6629/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00006630/// arguments being passed to the candidate. IsAssignmentOperator
6631/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00006632/// operator. NumContextualBoolArguments is the number of arguments
6633/// (at the beginning of the argument list) that will be contextually
6634/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00006635void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smithe54c3072013-05-05 15:51:06 +00006636 ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00006637 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006638 bool IsAssignmentOperator,
6639 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00006640 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006641 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006642
Douglas Gregora11693b2008-11-12 17:17:38 +00006643 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00006644 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
Craig Topperc3ec1492014-05-26 06:22:03 +00006645 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6646 Candidate.Function = nullptr;
Douglas Gregor1d248c52008-12-12 02:00:36 +00006647 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006648 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00006649 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smithe54c3072013-05-05 15:51:06 +00006650 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregora11693b2008-11-12 17:17:38 +00006651 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6652
6653 // Determine the implicit conversion sequences for each of the
6654 // arguments.
6655 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00006656 Candidate.ExplicitCallArguments = Args.size();
6657 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00006658 // C++ [over.match.oper]p4:
6659 // For the built-in assignment operators, conversions of the
6660 // left operand are restricted as follows:
6661 // -- no temporaries are introduced to hold the left operand, and
6662 // -- no user-defined conversions are applied to the left
6663 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00006664 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00006665 //
6666 // We block these conversions by turning off user-defined
6667 // conversions, since that is the only way that initialization of
6668 // a reference to a non-class type can occur from something that
6669 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006670 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006671 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006672 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006673 Candidate.Conversions[ArgIdx]
6674 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006675 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006676 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006677 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006678 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006679 /*InOverloadResolution=*/false,
6680 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006681 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006682 }
John McCall0d1da222010-01-12 00:44:57 +00006683 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006684 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006685 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006686 break;
6687 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006688 }
6689}
6690
Craig Toppercd7b0332013-07-01 06:29:40 +00006691namespace {
6692
Douglas Gregora11693b2008-11-12 17:17:38 +00006693/// BuiltinCandidateTypeSet - A set of types that will be used for the
6694/// candidate operator functions for built-in operators (C++
6695/// [over.built]). The types are separated into pointer types and
6696/// enumeration types.
6697class BuiltinCandidateTypeSet {
6698 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006699 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006700
6701 /// PointerTypes - The set of pointer types that will be used in the
6702 /// built-in candidates.
6703 TypeSet PointerTypes;
6704
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006705 /// MemberPointerTypes - The set of member pointer types that will be
6706 /// used in the built-in candidates.
6707 TypeSet MemberPointerTypes;
6708
Douglas Gregora11693b2008-11-12 17:17:38 +00006709 /// EnumerationTypes - The set of enumeration types that will be
6710 /// used in the built-in candidates.
6711 TypeSet EnumerationTypes;
6712
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006713 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006714 /// candidates.
6715 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006716
6717 /// \brief A flag indicating non-record types are viable candidates
6718 bool HasNonRecordTypes;
6719
6720 /// \brief A flag indicating whether either arithmetic or enumeration types
6721 /// were present in the candidate set.
6722 bool HasArithmeticOrEnumeralTypes;
6723
Douglas Gregor80af3132011-05-21 23:15:46 +00006724 /// \brief A flag indicating whether the nullptr type was present in the
6725 /// candidate set.
6726 bool HasNullPtrType;
6727
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006728 /// Sema - The semantic analysis instance where we are building the
6729 /// candidate type set.
6730 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006731
Douglas Gregora11693b2008-11-12 17:17:38 +00006732 /// Context - The AST context in which we will build the type sets.
6733 ASTContext &Context;
6734
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006735 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6736 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006737 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006738
6739public:
6740 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006741 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006742
Mike Stump11289f42009-09-09 15:08:12 +00006743 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006744 : HasNonRecordTypes(false),
6745 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006746 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006747 SemaRef(SemaRef),
6748 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006749
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006750 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006751 SourceLocation Loc,
6752 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006753 bool AllowExplicitConversions,
6754 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006755
6756 /// pointer_begin - First pointer type found;
6757 iterator pointer_begin() { return PointerTypes.begin(); }
6758
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006759 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006760 iterator pointer_end() { return PointerTypes.end(); }
6761
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006762 /// member_pointer_begin - First member pointer type found;
6763 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6764
6765 /// member_pointer_end - Past the last member pointer type found;
6766 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6767
Douglas Gregora11693b2008-11-12 17:17:38 +00006768 /// enumeration_begin - First enumeration type found;
6769 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6770
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006771 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006772 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006773
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006774 iterator vector_begin() { return VectorTypes.begin(); }
6775 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006776
6777 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6778 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006779 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006780};
6781
Craig Toppercd7b0332013-07-01 06:29:40 +00006782} // end anonymous namespace
6783
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006784/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006785/// the set of pointer types along with any more-qualified variants of
6786/// that type. For example, if @p Ty is "int const *", this routine
6787/// will add "int const *", "int const volatile *", "int const
6788/// restrict *", and "int const volatile restrict *" to the set of
6789/// pointer types. Returns true if the add of @p Ty itself succeeded,
6790/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006791///
6792/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006793bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006794BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6795 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006796
Douglas Gregora11693b2008-11-12 17:17:38 +00006797 // Insert this type.
David Blaikie82e95a32014-11-19 07:49:47 +00006798 if (!PointerTypes.insert(Ty).second)
Douglas Gregora11693b2008-11-12 17:17:38 +00006799 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006800
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006801 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006802 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006803 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006804 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006805 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6806 PointeeTy = PTy->getPointeeType();
6807 buildObjCPtr = true;
6808 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006809 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00006810 }
6811
Sebastian Redl4990a632009-11-18 20:39:26 +00006812 // Don't add qualified variants of arrays. For one, they're not allowed
6813 // (the qualifier would sink to the element type), and for another, the
6814 // only overload situation where it matters is subscript or pointer +- int,
6815 // and those shouldn't have qualifier variants anyway.
6816 if (PointeeTy->isArrayType())
6817 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006818
John McCall8ccfcb52009-09-24 19:53:00 +00006819 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006820 bool hasVolatile = VisibleQuals.hasVolatile();
6821 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006822
John McCall8ccfcb52009-09-24 19:53:00 +00006823 // Iterate through all strict supersets of BaseCVR.
6824 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6825 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006826 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006827 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006828
6829 // Skip over restrict if no restrict found anywhere in the types, or if
6830 // the type cannot be restrict-qualified.
6831 if ((CVR & Qualifiers::Restrict) &&
6832 (!hasRestrict ||
6833 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6834 continue;
6835
6836 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00006837 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006838
6839 // Build qualified pointer type.
6840 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006841 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00006842 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006843 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00006844 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6845
6846 // Insert qualified pointer type.
6847 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00006848 }
6849
6850 return true;
6851}
6852
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006853/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6854/// to the set of pointer types along with any more-qualified variants of
6855/// that type. For example, if @p Ty is "int const *", this routine
6856/// will add "int const *", "int const volatile *", "int const
6857/// restrict *", and "int const volatile restrict *" to the set of
6858/// pointer types. Returns true if the add of @p Ty itself succeeded,
6859/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006860///
6861/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006862bool
6863BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6864 QualType Ty) {
6865 // Insert this type.
David Blaikie82e95a32014-11-19 07:49:47 +00006866 if (!MemberPointerTypes.insert(Ty).second)
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006867 return false;
6868
John McCall8ccfcb52009-09-24 19:53:00 +00006869 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6870 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006871
John McCall8ccfcb52009-09-24 19:53:00 +00006872 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006873 // Don't add qualified variants of arrays. For one, they're not allowed
6874 // (the qualifier would sink to the element type), and for another, the
6875 // only overload situation where it matters is subscript or pointer +- int,
6876 // and those shouldn't have qualifier variants anyway.
6877 if (PointeeTy->isArrayType())
6878 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006879 const Type *ClassTy = PointerTy->getClass();
6880
6881 // Iterate through all strict supersets of the pointee type's CVR
6882 // qualifiers.
6883 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6884 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6885 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006886
John McCall8ccfcb52009-09-24 19:53:00 +00006887 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006888 MemberPointerTypes.insert(
6889 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006890 }
6891
6892 return true;
6893}
6894
Douglas Gregora11693b2008-11-12 17:17:38 +00006895/// AddTypesConvertedFrom - Add each of the types to which the type @p
6896/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006897/// primarily interested in pointer types and enumeration types. We also
6898/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006899/// AllowUserConversions is true if we should look at the conversion
6900/// functions of a class type, and AllowExplicitConversions if we
6901/// should also include the explicit conversion functions of a class
6902/// type.
Mike Stump11289f42009-09-09 15:08:12 +00006903void
Douglas Gregor5fb53972009-01-14 15:45:31 +00006904BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006905 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006906 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006907 bool AllowExplicitConversions,
6908 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006909 // Only deal with canonical types.
6910 Ty = Context.getCanonicalType(Ty);
6911
6912 // Look through reference types; they aren't part of the type of an
6913 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006914 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00006915 Ty = RefTy->getPointeeType();
6916
John McCall33ddac02011-01-19 10:06:00 +00006917 // If we're dealing with an array type, decay to the pointer.
6918 if (Ty->isArrayType())
6919 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6920
6921 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006922 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00006923
Chandler Carruth00a38332010-12-13 01:44:01 +00006924 // Flag if we ever add a non-record type.
6925 const RecordType *TyRec = Ty->getAs<RecordType>();
6926 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6927
Chandler Carruth00a38332010-12-13 01:44:01 +00006928 // Flag if we encounter an arithmetic type.
6929 HasArithmeticOrEnumeralTypes =
6930 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6931
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006932 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6933 PointerTypes.insert(Ty);
6934 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006935 // Insert our type, and its more-qualified variants, into the set
6936 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006937 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00006938 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006939 } else if (Ty->isMemberPointerType()) {
6940 // Member pointers are far easier, since the pointee can't be converted.
6941 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6942 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00006943 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006944 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00006945 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006946 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006947 // We treat vector types as arithmetic types in many contexts as an
6948 // extension.
6949 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006950 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00006951 } else if (Ty->isNullPtrType()) {
6952 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00006953 } else if (AllowUserConversions && TyRec) {
6954 // No conversion functions in incomplete types.
6955 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6956 return;
Mike Stump11289f42009-09-09 15:08:12 +00006957
Chandler Carruth00a38332010-12-13 01:44:01 +00006958 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00006959 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006960 if (isa<UsingShadowDecl>(D))
6961 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00006962
Chandler Carruth00a38332010-12-13 01:44:01 +00006963 // Skip conversion function templates; they don't tell us anything
6964 // about which builtin types we can convert to.
6965 if (isa<FunctionTemplateDecl>(D))
6966 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006967
Chandler Carruth00a38332010-12-13 01:44:01 +00006968 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6969 if (AllowExplicitConversions || !Conv->isExplicit()) {
6970 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6971 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006972 }
6973 }
6974 }
6975}
6976
Douglas Gregor84605ae2009-08-24 13:43:27 +00006977/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6978/// the volatile- and non-volatile-qualified assignment operators for the
6979/// given type to the candidate set.
6980static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6981 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00006982 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006983 OverloadCandidateSet &CandidateSet) {
6984 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00006985
Douglas Gregor84605ae2009-08-24 13:43:27 +00006986 // T& operator=(T&, T)
6987 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6988 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00006989 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006990 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00006991
Douglas Gregor84605ae2009-08-24 13:43:27 +00006992 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6993 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00006994 ParamTypes[0]
6995 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00006996 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00006997 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00006998 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00006999 }
7000}
Mike Stump11289f42009-09-09 15:08:12 +00007001
Sebastian Redl1054fae2009-10-25 17:03:50 +00007002/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7003/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007004static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7005 Qualifiers VRQuals;
7006 const RecordType *TyRec;
7007 if (const MemberPointerType *RHSMPType =
7008 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00007009 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007010 else
7011 TyRec = ArgExpr->getType()->getAs<RecordType>();
7012 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00007013 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007014 VRQuals.addVolatile();
7015 VRQuals.addRestrict();
7016 return VRQuals;
7017 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007018
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007019 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00007020 if (!ClassDecl->hasDefinition())
7021 return VRQuals;
7022
Benjamin Kramerb4ef6682015-02-06 17:25:10 +00007023 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
John McCallda4458e2010-03-31 01:36:47 +00007024 if (isa<UsingShadowDecl>(D))
7025 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7026 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007027 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7028 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7029 CanTy = ResTypeRef->getPointeeType();
7030 // Need to go down the pointer/mempointer chain and add qualifiers
7031 // as see them.
7032 bool done = false;
7033 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00007034 if (CanTy.isRestrictQualified())
7035 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007036 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7037 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007038 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007039 CanTy->getAs<MemberPointerType>())
7040 CanTy = ResTypeMPtr->getPointeeType();
7041 else
7042 done = true;
7043 if (CanTy.isVolatileQualified())
7044 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007045 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7046 return VRQuals;
7047 }
7048 }
7049 }
7050 return VRQuals;
7051}
John McCall52872982010-11-13 05:51:15 +00007052
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007053namespace {
John McCall52872982010-11-13 05:51:15 +00007054
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007055/// \brief Helper class to manage the addition of builtin operator overload
7056/// candidates. It provides shared state and utility methods used throughout
7057/// the process, as well as a helper method to add each group of builtin
7058/// operator overloads from the standard to a candidate set.
7059class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007060 // Common instance state available to all overload candidate addition methods.
7061 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00007062 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007063 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00007064 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007065 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00007066 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007067
Chandler Carruthc6586e52010-12-12 10:35:00 +00007068 // Define some constants used to index and iterate over the arithemetic types
7069 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00007070 // The "promoted arithmetic types" are the arithmetic
7071 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00007072 static const unsigned FirstIntegralType = 3;
Richard Smith521ecc12012-06-10 08:00:26 +00007073 static const unsigned LastIntegralType = 20;
John McCall52872982010-11-13 05:51:15 +00007074 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith521ecc12012-06-10 08:00:26 +00007075 LastPromotedIntegralType = 11;
John McCall52872982010-11-13 05:51:15 +00007076 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith521ecc12012-06-10 08:00:26 +00007077 LastPromotedArithmeticType = 11;
7078 static const unsigned NumArithmeticTypes = 20;
John McCall52872982010-11-13 05:51:15 +00007079
Chandler Carruthc6586e52010-12-12 10:35:00 +00007080 /// \brief Get the canonical type for a given arithmetic type index.
7081 CanQualType getArithmeticType(unsigned index) {
7082 assert(index < NumArithmeticTypes);
7083 static CanQualType ASTContext::* const
7084 ArithmeticTypes[NumArithmeticTypes] = {
7085 // Start of promoted types.
7086 &ASTContext::FloatTy,
7087 &ASTContext::DoubleTy,
7088 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00007089
Chandler Carruthc6586e52010-12-12 10:35:00 +00007090 // Start of integral types.
7091 &ASTContext::IntTy,
7092 &ASTContext::LongTy,
7093 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007094 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007095 &ASTContext::UnsignedIntTy,
7096 &ASTContext::UnsignedLongTy,
7097 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00007098 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00007099 // End of promoted types.
7100
7101 &ASTContext::BoolTy,
7102 &ASTContext::CharTy,
7103 &ASTContext::WCharTy,
7104 &ASTContext::Char16Ty,
7105 &ASTContext::Char32Ty,
7106 &ASTContext::SignedCharTy,
7107 &ASTContext::ShortTy,
7108 &ASTContext::UnsignedCharTy,
7109 &ASTContext::UnsignedShortTy,
7110 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00007111 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00007112 };
7113 return S.Context.*ArithmeticTypes[index];
7114 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007115
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007116 /// \brief Gets the canonical type resulting from the usual arithemetic
7117 /// converions for the given arithmetic types.
7118 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
7119 // Accelerator table for performing the usual arithmetic conversions.
7120 // The rules are basically:
7121 // - if either is floating-point, use the wider floating-point
7122 // - if same signedness, use the higher rank
7123 // - if same size, use unsigned of the higher rank
7124 // - use the larger type
7125 // These rules, together with the axiom that higher ranks are
7126 // never smaller, are sufficient to precompute all of these results
7127 // *except* when dealing with signed types of higher rank.
7128 // (we could precompute SLL x UI for all known platforms, but it's
7129 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00007130 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007131 enum PromotedType {
Richard Smith521ecc12012-06-10 08:00:26 +00007132 Dep=-1,
7133 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007134 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00007135 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007136 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00007137/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
7138/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
7139/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
7140/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
7141/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
7142/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
7143/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
7144/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
7145/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
7146/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
7147/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007148 };
7149
7150 assert(L < LastPromotedArithmeticType);
7151 assert(R < LastPromotedArithmeticType);
7152 int Idx = ConversionsTable[L][R];
7153
7154 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007155 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007156
7157 // Slow path: we need to compare widths.
7158 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007159 CanQualType LT = getArithmeticType(L),
7160 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007161 unsigned LW = S.Context.getIntWidth(LT),
7162 RW = S.Context.getIntWidth(RT);
7163
7164 // If they're different widths, use the signed type.
7165 if (LW > RW) return LT;
7166 else if (LW < RW) return RT;
7167
7168 // Otherwise, use the unsigned type of the signed type's rank.
7169 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
7170 assert(L == SLL || R == SLL);
7171 return S.Context.UnsignedLongLongTy;
7172 }
7173
Chandler Carruth5659c0c2010-12-12 09:22:45 +00007174 /// \brief Helper method to factor out the common pattern of adding overloads
7175 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007176 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007177 bool HasVolatile,
7178 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007179 QualType ParamTypes[2] = {
7180 S.Context.getLValueReferenceType(CandidateTy),
7181 S.Context.IntTy
7182 };
7183
7184 // Non-volatile version.
Richard Smithe54c3072013-05-05 15:51:06 +00007185 if (Args.size() == 1)
7186 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007187 else
Richard Smithe54c3072013-05-05 15:51:06 +00007188 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007189
7190 // Use a heuristic to reduce number of builtin candidates in the set:
7191 // add volatile version only if there are conversions to a volatile type.
7192 if (HasVolatile) {
7193 ParamTypes[0] =
7194 S.Context.getLValueReferenceType(
7195 S.Context.getVolatileType(CandidateTy));
Richard Smithe54c3072013-05-05 15:51:06 +00007196 if (Args.size() == 1)
7197 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007198 else
Richard Smithe54c3072013-05-05 15:51:06 +00007199 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007200 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007201
7202 // Add restrict version only if there are conversions to a restrict type
7203 // and our candidate type is a non-restrict-qualified pointer.
7204 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7205 !CandidateTy.isRestrictQualified()) {
7206 ParamTypes[0]
7207 = S.Context.getLValueReferenceType(
7208 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smithe54c3072013-05-05 15:51:06 +00007209 if (Args.size() == 1)
7210 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007211 else
Richard Smithe54c3072013-05-05 15:51:06 +00007212 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007213
7214 if (HasVolatile) {
7215 ParamTypes[0]
7216 = S.Context.getLValueReferenceType(
7217 S.Context.getCVRQualifiedType(CandidateTy,
7218 (Qualifiers::Volatile |
7219 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007220 if (Args.size() == 1)
7221 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007222 else
Richard Smithe54c3072013-05-05 15:51:06 +00007223 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007224 }
7225 }
7226
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007227 }
7228
7229public:
7230 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007231 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007232 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007233 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007234 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007235 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007236 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007237 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007238 HasArithmeticOrEnumeralCandidateType(
7239 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007240 CandidateTypes(CandidateTypes),
7241 CandidateSet(CandidateSet) {
7242 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007243 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007244 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007245 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007246 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007247 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007248 assert(getArithmeticType(FirstPromotedArithmeticType)
7249 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007250 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007251 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007252 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007253 "Invalid last promoted arithmetic type");
7254 }
7255
7256 // C++ [over.built]p3:
7257 //
7258 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7259 // is either volatile or empty, there exist candidate operator
7260 // functions of the form
7261 //
7262 // VQ T& operator++(VQ T&);
7263 // T operator++(VQ T&, int);
7264 //
7265 // C++ [over.built]p4:
7266 //
7267 // For every pair (T, VQ), where T is an arithmetic type other
7268 // than bool, and VQ is either volatile or empty, there exist
7269 // candidate operator functions of the form
7270 //
7271 // VQ T& operator--(VQ T&);
7272 // T operator--(VQ T&, int);
7273 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007274 if (!HasArithmeticOrEnumeralCandidateType)
7275 return;
7276
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007277 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7278 Arith < NumArithmeticTypes; ++Arith) {
7279 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007280 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007281 VisibleTypeConversionsQuals.hasVolatile(),
7282 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007283 }
7284 }
7285
7286 // C++ [over.built]p5:
7287 //
7288 // For every pair (T, VQ), where T is a cv-qualified or
7289 // cv-unqualified object type, and VQ is either volatile or
7290 // empty, there exist candidate operator functions of the form
7291 //
7292 // T*VQ& operator++(T*VQ&);
7293 // T*VQ& operator--(T*VQ&);
7294 // T* operator++(T*VQ&, int);
7295 // T* operator--(T*VQ&, int);
7296 void addPlusPlusMinusMinusPointerOverloads() {
7297 for (BuiltinCandidateTypeSet::iterator
7298 Ptr = CandidateTypes[0].pointer_begin(),
7299 PtrEnd = CandidateTypes[0].pointer_end();
7300 Ptr != PtrEnd; ++Ptr) {
7301 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007302 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007303 continue;
7304
7305 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007306 (!(*Ptr).isVolatileQualified() &&
7307 VisibleTypeConversionsQuals.hasVolatile()),
7308 (!(*Ptr).isRestrictQualified() &&
7309 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007310 }
7311 }
7312
7313 // C++ [over.built]p6:
7314 // For every cv-qualified or cv-unqualified object type T, there
7315 // exist candidate operator functions of the form
7316 //
7317 // T& operator*(T*);
7318 //
7319 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007320 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007321 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007322 // T& operator*(T*);
7323 void addUnaryStarPointerOverloads() {
7324 for (BuiltinCandidateTypeSet::iterator
7325 Ptr = CandidateTypes[0].pointer_begin(),
7326 PtrEnd = CandidateTypes[0].pointer_end();
7327 Ptr != PtrEnd; ++Ptr) {
7328 QualType ParamTy = *Ptr;
7329 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007330 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7331 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007332
Douglas Gregor02824322011-01-26 19:30:28 +00007333 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7334 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7335 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007336
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007337 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smithe54c3072013-05-05 15:51:06 +00007338 &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007339 }
7340 }
7341
7342 // C++ [over.built]p9:
7343 // For every promoted arithmetic type T, there exist candidate
7344 // operator functions of the form
7345 //
7346 // T operator+(T);
7347 // T operator-(T);
7348 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007349 if (!HasArithmeticOrEnumeralCandidateType)
7350 return;
7351
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007352 for (unsigned Arith = FirstPromotedArithmeticType;
7353 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007354 QualType ArithTy = getArithmeticType(Arith);
Richard Smithe54c3072013-05-05 15:51:06 +00007355 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007356 }
7357
7358 // Extension: We also add these operators for vector types.
7359 for (BuiltinCandidateTypeSet::iterator
7360 Vec = CandidateTypes[0].vector_begin(),
7361 VecEnd = CandidateTypes[0].vector_end();
7362 Vec != VecEnd; ++Vec) {
7363 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007364 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007365 }
7366 }
7367
7368 // C++ [over.built]p8:
7369 // For every type T, there exist candidate operator functions of
7370 // the form
7371 //
7372 // T* operator+(T*);
7373 void addUnaryPlusPointerOverloads() {
7374 for (BuiltinCandidateTypeSet::iterator
7375 Ptr = CandidateTypes[0].pointer_begin(),
7376 PtrEnd = CandidateTypes[0].pointer_end();
7377 Ptr != PtrEnd; ++Ptr) {
7378 QualType ParamTy = *Ptr;
Richard Smithe54c3072013-05-05 15:51:06 +00007379 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007380 }
7381 }
7382
7383 // C++ [over.built]p10:
7384 // For every promoted integral type T, there exist candidate
7385 // operator functions of the form
7386 //
7387 // T operator~(T);
7388 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007389 if (!HasArithmeticOrEnumeralCandidateType)
7390 return;
7391
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007392 for (unsigned Int = FirstPromotedIntegralType;
7393 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007394 QualType IntTy = getArithmeticType(Int);
Richard Smithe54c3072013-05-05 15:51:06 +00007395 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007396 }
7397
7398 // Extension: We also add this operator for vector types.
7399 for (BuiltinCandidateTypeSet::iterator
7400 Vec = CandidateTypes[0].vector_begin(),
7401 VecEnd = CandidateTypes[0].vector_end();
7402 Vec != VecEnd; ++Vec) {
7403 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007404 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007405 }
7406 }
7407
7408 // C++ [over.match.oper]p16:
7409 // For every pointer to member type T, there exist candidate operator
7410 // functions of the form
7411 //
7412 // bool operator==(T,T);
7413 // bool operator!=(T,T);
7414 void addEqualEqualOrNotEqualMemberPointerOverloads() {
7415 /// Set of (canonical) types that we've already handled.
7416 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7417
Richard Smithe54c3072013-05-05 15:51:06 +00007418 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007419 for (BuiltinCandidateTypeSet::iterator
7420 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7421 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7422 MemPtr != MemPtrEnd;
7423 ++MemPtr) {
7424 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007425 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007426 continue;
7427
7428 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007429 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007430 }
7431 }
7432 }
7433
7434 // C++ [over.built]p15:
7435 //
Douglas Gregor80af3132011-05-21 23:15:46 +00007436 // For every T, where T is an enumeration type, a pointer type, or
7437 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007438 //
7439 // bool operator<(T, T);
7440 // bool operator>(T, T);
7441 // bool operator<=(T, T);
7442 // bool operator>=(T, T);
7443 // bool operator==(T, T);
7444 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007445 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007446 // C++ [over.match.oper]p3:
7447 // [...]the built-in candidates include all of the candidate operator
7448 // functions defined in 13.6 that, compared to the given operator, [...]
7449 // do not have the same parameter-type-list as any non-template non-member
7450 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007451 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007452 // Note that in practice, this only affects enumeration types because there
7453 // aren't any built-in candidates of record type, and a user-defined operator
7454 // must have an operand of record or enumeration type. Also, the only other
7455 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007456 // cannot be overloaded for enumeration types, so this is the only place
7457 // where we must suppress candidates like this.
7458 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7459 UserDefinedBinaryOperators;
7460
Richard Smithe54c3072013-05-05 15:51:06 +00007461 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007462 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7463 CandidateTypes[ArgIdx].enumeration_end()) {
7464 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7465 CEnd = CandidateSet.end();
7466 C != CEnd; ++C) {
7467 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7468 continue;
7469
Eli Friedman14f082b2012-09-18 21:52:24 +00007470 if (C->Function->isFunctionTemplateSpecialization())
7471 continue;
7472
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007473 QualType FirstParamType =
7474 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7475 QualType SecondParamType =
7476 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7477
7478 // Skip if either parameter isn't of enumeral type.
7479 if (!FirstParamType->isEnumeralType() ||
7480 !SecondParamType->isEnumeralType())
7481 continue;
7482
7483 // Add this operator to the set of known user-defined operators.
7484 UserDefinedBinaryOperators.insert(
7485 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7486 S.Context.getCanonicalType(SecondParamType)));
7487 }
7488 }
7489 }
7490
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007491 /// Set of (canonical) types that we've already handled.
7492 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7493
Richard Smithe54c3072013-05-05 15:51:06 +00007494 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007495 for (BuiltinCandidateTypeSet::iterator
7496 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7497 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7498 Ptr != PtrEnd; ++Ptr) {
7499 // Don't add the same builtin candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007500 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007501 continue;
7502
7503 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007504 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007505 }
7506 for (BuiltinCandidateTypeSet::iterator
7507 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7508 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7509 Enum != EnumEnd; ++Enum) {
7510 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7511
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007512 // Don't add the same builtin candidate twice, or if a user defined
7513 // candidate exists.
David Blaikie82e95a32014-11-19 07:49:47 +00007514 if (!AddedTypes.insert(CanonType).second ||
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007515 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7516 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007517 continue;
7518
7519 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007520 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007521 }
Douglas Gregor80af3132011-05-21 23:15:46 +00007522
7523 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7524 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
David Blaikie82e95a32014-11-19 07:49:47 +00007525 if (AddedTypes.insert(NullPtrTy).second &&
Richard Smithe54c3072013-05-05 15:51:06 +00007526 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor80af3132011-05-21 23:15:46 +00007527 NullPtrTy))) {
7528 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007529 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor80af3132011-05-21 23:15:46 +00007530 CandidateSet);
7531 }
7532 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007533 }
7534 }
7535
7536 // C++ [over.built]p13:
7537 //
7538 // For every cv-qualified or cv-unqualified object type T
7539 // there exist candidate operator functions of the form
7540 //
7541 // T* operator+(T*, ptrdiff_t);
7542 // T& operator[](T*, ptrdiff_t); [BELOW]
7543 // T* operator-(T*, ptrdiff_t);
7544 // T* operator+(ptrdiff_t, T*);
7545 // T& operator[](ptrdiff_t, T*); [BELOW]
7546 //
7547 // C++ [over.built]p14:
7548 //
7549 // For every T, where T is a pointer to object type, there
7550 // exist candidate operator functions of the form
7551 //
7552 // ptrdiff_t operator-(T, T);
7553 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7554 /// Set of (canonical) types that we've already handled.
7555 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7556
7557 for (int Arg = 0; Arg < 2; ++Arg) {
Eric Christopher9207a522015-08-21 16:24:01 +00007558 QualType AsymmetricParamTypes[2] = {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007559 S.Context.getPointerDiffType(),
7560 S.Context.getPointerDiffType(),
7561 };
7562 for (BuiltinCandidateTypeSet::iterator
7563 Ptr = CandidateTypes[Arg].pointer_begin(),
7564 PtrEnd = CandidateTypes[Arg].pointer_end();
7565 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00007566 QualType PointeeTy = (*Ptr)->getPointeeType();
7567 if (!PointeeTy->isObjectType())
7568 continue;
7569
Eric Christopher9207a522015-08-21 16:24:01 +00007570 AsymmetricParamTypes[Arg] = *Ptr;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007571 if (Arg == 0 || Op == OO_Plus) {
7572 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7573 // T* operator+(ptrdiff_t, T*);
Eric Christopher9207a522015-08-21 16:24:01 +00007574 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007575 }
7576 if (Op == OO_Minus) {
7577 // ptrdiff_t operator-(T, T);
David Blaikie82e95a32014-11-19 07:49:47 +00007578 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007579 continue;
7580
7581 QualType ParamTypes[2] = { *Ptr, *Ptr };
7582 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smithe54c3072013-05-05 15:51:06 +00007583 Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007584 }
7585 }
7586 }
7587 }
7588
7589 // C++ [over.built]p12:
7590 //
7591 // For every pair of promoted arithmetic types L and R, there
7592 // exist candidate operator functions of the form
7593 //
7594 // LR operator*(L, R);
7595 // LR operator/(L, R);
7596 // LR operator+(L, R);
7597 // LR operator-(L, R);
7598 // bool operator<(L, R);
7599 // bool operator>(L, R);
7600 // bool operator<=(L, R);
7601 // bool operator>=(L, R);
7602 // bool operator==(L, R);
7603 // bool operator!=(L, R);
7604 //
7605 // where LR is the result of the usual arithmetic conversions
7606 // between types L and R.
7607 //
7608 // C++ [over.built]p24:
7609 //
7610 // For every pair of promoted arithmetic types L and R, there exist
7611 // candidate operator functions of the form
7612 //
7613 // LR operator?(bool, L, R);
7614 //
7615 // where LR is the result of the usual arithmetic conversions
7616 // between types L and R.
7617 // Our candidates ignore the first parameter.
7618 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007619 if (!HasArithmeticOrEnumeralCandidateType)
7620 return;
7621
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007622 for (unsigned Left = FirstPromotedArithmeticType;
7623 Left < LastPromotedArithmeticType; ++Left) {
7624 for (unsigned Right = FirstPromotedArithmeticType;
7625 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007626 QualType LandR[2] = { getArithmeticType(Left),
7627 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007628 QualType Result =
7629 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007630 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007631 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007632 }
7633 }
7634
7635 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7636 // conditional operator for vector types.
7637 for (BuiltinCandidateTypeSet::iterator
7638 Vec1 = CandidateTypes[0].vector_begin(),
7639 Vec1End = CandidateTypes[0].vector_end();
7640 Vec1 != Vec1End; ++Vec1) {
7641 for (BuiltinCandidateTypeSet::iterator
7642 Vec2 = CandidateTypes[1].vector_begin(),
7643 Vec2End = CandidateTypes[1].vector_end();
7644 Vec2 != Vec2End; ++Vec2) {
7645 QualType LandR[2] = { *Vec1, *Vec2 };
7646 QualType Result = S.Context.BoolTy;
7647 if (!isComparison) {
7648 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7649 Result = *Vec1;
7650 else
7651 Result = *Vec2;
7652 }
7653
Richard Smithe54c3072013-05-05 15:51:06 +00007654 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007655 }
7656 }
7657 }
7658
7659 // C++ [over.built]p17:
7660 //
7661 // For every pair of promoted integral types L and R, there
7662 // exist candidate operator functions of the form
7663 //
7664 // LR operator%(L, R);
7665 // LR operator&(L, R);
7666 // LR operator^(L, R);
7667 // LR operator|(L, R);
7668 // L operator<<(L, R);
7669 // L operator>>(L, R);
7670 //
7671 // where LR is the result of the usual arithmetic conversions
7672 // between types L and R.
7673 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007674 if (!HasArithmeticOrEnumeralCandidateType)
7675 return;
7676
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007677 for (unsigned Left = FirstPromotedIntegralType;
7678 Left < LastPromotedIntegralType; ++Left) {
7679 for (unsigned Right = FirstPromotedIntegralType;
7680 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007681 QualType LandR[2] = { getArithmeticType(Left),
7682 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007683 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7684 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007685 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007686 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007687 }
7688 }
7689 }
7690
7691 // C++ [over.built]p20:
7692 //
7693 // For every pair (T, VQ), where T is an enumeration or
7694 // pointer to member type and VQ is either volatile or
7695 // empty, there exist candidate operator functions of the form
7696 //
7697 // VQ T& operator=(VQ T&, T);
7698 void addAssignmentMemberPointerOrEnumeralOverloads() {
7699 /// Set of (canonical) types that we've already handled.
7700 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7701
7702 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7703 for (BuiltinCandidateTypeSet::iterator
7704 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7705 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7706 Enum != EnumEnd; ++Enum) {
David Blaikie82e95a32014-11-19 07:49:47 +00007707 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007708 continue;
7709
Richard Smithe54c3072013-05-05 15:51:06 +00007710 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007711 }
7712
7713 for (BuiltinCandidateTypeSet::iterator
7714 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7715 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7716 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00007717 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007718 continue;
7719
Richard Smithe54c3072013-05-05 15:51:06 +00007720 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007721 }
7722 }
7723 }
7724
7725 // C++ [over.built]p19:
7726 //
7727 // For every pair (T, VQ), where T is any type and VQ is either
7728 // volatile or empty, there exist candidate operator functions
7729 // of the form
7730 //
7731 // T*VQ& operator=(T*VQ&, T*);
7732 //
7733 // C++ [over.built]p21:
7734 //
7735 // For every pair (T, VQ), where T is a cv-qualified or
7736 // cv-unqualified object type and VQ is either volatile or
7737 // empty, there exist candidate operator functions of the form
7738 //
7739 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7740 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7741 void addAssignmentPointerOverloads(bool isEqualOp) {
7742 /// Set of (canonical) types that we've already handled.
7743 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7744
7745 for (BuiltinCandidateTypeSet::iterator
7746 Ptr = CandidateTypes[0].pointer_begin(),
7747 PtrEnd = CandidateTypes[0].pointer_end();
7748 Ptr != PtrEnd; ++Ptr) {
7749 // If this is operator=, keep track of the builtin candidates we added.
7750 if (isEqualOp)
7751 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007752 else if (!(*Ptr)->getPointeeType()->isObjectType())
7753 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007754
7755 // non-volatile version
7756 QualType ParamTypes[2] = {
7757 S.Context.getLValueReferenceType(*Ptr),
7758 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7759 };
Richard Smithe54c3072013-05-05 15:51:06 +00007760 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007761 /*IsAssigmentOperator=*/ isEqualOp);
7762
Douglas Gregor5bee2582012-06-04 00:15:09 +00007763 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7764 VisibleTypeConversionsQuals.hasVolatile();
7765 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007766 // volatile version
7767 ParamTypes[0] =
7768 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007769 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007770 /*IsAssigmentOperator=*/isEqualOp);
7771 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007772
7773 if (!(*Ptr).isRestrictQualified() &&
7774 VisibleTypeConversionsQuals.hasRestrict()) {
7775 // restrict version
7776 ParamTypes[0]
7777 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007778 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007779 /*IsAssigmentOperator=*/isEqualOp);
7780
7781 if (NeedVolatile) {
7782 // volatile restrict version
7783 ParamTypes[0]
7784 = S.Context.getLValueReferenceType(
7785 S.Context.getCVRQualifiedType(*Ptr,
7786 (Qualifiers::Volatile |
7787 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007788 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007789 /*IsAssigmentOperator=*/isEqualOp);
7790 }
7791 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007792 }
7793
7794 if (isEqualOp) {
7795 for (BuiltinCandidateTypeSet::iterator
7796 Ptr = CandidateTypes[1].pointer_begin(),
7797 PtrEnd = CandidateTypes[1].pointer_end();
7798 Ptr != PtrEnd; ++Ptr) {
7799 // Make sure we don't add the same candidate twice.
David Blaikie82e95a32014-11-19 07:49:47 +00007800 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007801 continue;
7802
Chandler Carruth8e543b32010-12-12 08:17:55 +00007803 QualType ParamTypes[2] = {
7804 S.Context.getLValueReferenceType(*Ptr),
7805 *Ptr,
7806 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007807
7808 // non-volatile version
Richard Smithe54c3072013-05-05 15:51:06 +00007809 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007810 /*IsAssigmentOperator=*/true);
7811
Douglas Gregor5bee2582012-06-04 00:15:09 +00007812 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7813 VisibleTypeConversionsQuals.hasVolatile();
7814 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007815 // volatile version
7816 ParamTypes[0] =
7817 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007818 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7819 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007820 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007821
7822 if (!(*Ptr).isRestrictQualified() &&
7823 VisibleTypeConversionsQuals.hasRestrict()) {
7824 // restrict version
7825 ParamTypes[0]
7826 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007827 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7828 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007829
7830 if (NeedVolatile) {
7831 // volatile restrict version
7832 ParamTypes[0]
7833 = S.Context.getLValueReferenceType(
7834 S.Context.getCVRQualifiedType(*Ptr,
7835 (Qualifiers::Volatile |
7836 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007837 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7838 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007839 }
7840 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007841 }
7842 }
7843 }
7844
7845 // C++ [over.built]p18:
7846 //
7847 // For every triple (L, VQ, R), where L is an arithmetic type,
7848 // VQ is either volatile or empty, and R is a promoted
7849 // arithmetic type, there exist candidate operator functions of
7850 // the form
7851 //
7852 // VQ L& operator=(VQ L&, R);
7853 // VQ L& operator*=(VQ L&, R);
7854 // VQ L& operator/=(VQ L&, R);
7855 // VQ L& operator+=(VQ L&, R);
7856 // VQ L& operator-=(VQ L&, R);
7857 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007858 if (!HasArithmeticOrEnumeralCandidateType)
7859 return;
7860
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007861 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7862 for (unsigned Right = FirstPromotedArithmeticType;
7863 Right < LastPromotedArithmeticType; ++Right) {
7864 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007865 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007866
7867 // Add this built-in operator as a candidate (VQ is empty).
7868 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007869 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007870 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007871 /*IsAssigmentOperator=*/isEqualOp);
7872
7873 // Add this built-in operator as a candidate (VQ is 'volatile').
7874 if (VisibleTypeConversionsQuals.hasVolatile()) {
7875 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007876 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007877 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007878 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007879 /*IsAssigmentOperator=*/isEqualOp);
7880 }
7881 }
7882 }
7883
7884 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7885 for (BuiltinCandidateTypeSet::iterator
7886 Vec1 = CandidateTypes[0].vector_begin(),
7887 Vec1End = CandidateTypes[0].vector_end();
7888 Vec1 != Vec1End; ++Vec1) {
7889 for (BuiltinCandidateTypeSet::iterator
7890 Vec2 = CandidateTypes[1].vector_begin(),
7891 Vec2End = CandidateTypes[1].vector_end();
7892 Vec2 != Vec2End; ++Vec2) {
7893 QualType ParamTypes[2];
7894 ParamTypes[1] = *Vec2;
7895 // Add this built-in operator as a candidate (VQ is empty).
7896 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smithe54c3072013-05-05 15:51:06 +00007897 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007898 /*IsAssigmentOperator=*/isEqualOp);
7899
7900 // Add this built-in operator as a candidate (VQ is 'volatile').
7901 if (VisibleTypeConversionsQuals.hasVolatile()) {
7902 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7903 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007904 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007905 /*IsAssigmentOperator=*/isEqualOp);
7906 }
7907 }
7908 }
7909 }
7910
7911 // C++ [over.built]p22:
7912 //
7913 // For every triple (L, VQ, R), where L is an integral type, VQ
7914 // is either volatile or empty, and R is a promoted integral
7915 // type, there exist candidate operator functions of the form
7916 //
7917 // VQ L& operator%=(VQ L&, R);
7918 // VQ L& operator<<=(VQ L&, R);
7919 // VQ L& operator>>=(VQ L&, R);
7920 // VQ L& operator&=(VQ L&, R);
7921 // VQ L& operator^=(VQ L&, R);
7922 // VQ L& operator|=(VQ L&, R);
7923 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007924 if (!HasArithmeticOrEnumeralCandidateType)
7925 return;
7926
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007927 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7928 for (unsigned Right = FirstPromotedIntegralType;
7929 Right < LastPromotedIntegralType; ++Right) {
7930 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007931 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007932
7933 // Add this built-in operator as a candidate (VQ is empty).
7934 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007935 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007936 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007937 if (VisibleTypeConversionsQuals.hasVolatile()) {
7938 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00007939 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007940 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7941 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007942 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007943 }
7944 }
7945 }
7946 }
7947
7948 // C++ [over.operator]p23:
7949 //
7950 // There also exist candidate operator functions of the form
7951 //
7952 // bool operator!(bool);
7953 // bool operator&&(bool, bool);
7954 // bool operator||(bool, bool);
7955 void addExclaimOverload() {
7956 QualType ParamTy = S.Context.BoolTy;
Richard Smithe54c3072013-05-05 15:51:06 +00007957 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007958 /*IsAssignmentOperator=*/false,
7959 /*NumContextualBoolArguments=*/1);
7960 }
7961 void addAmpAmpOrPipePipeOverload() {
7962 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007963 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007964 /*IsAssignmentOperator=*/false,
7965 /*NumContextualBoolArguments=*/2);
7966 }
7967
7968 // C++ [over.built]p13:
7969 //
7970 // For every cv-qualified or cv-unqualified object type T there
7971 // exist candidate operator functions of the form
7972 //
7973 // T* operator+(T*, ptrdiff_t); [ABOVE]
7974 // T& operator[](T*, ptrdiff_t);
7975 // T* operator-(T*, ptrdiff_t); [ABOVE]
7976 // T* operator+(ptrdiff_t, T*); [ABOVE]
7977 // T& operator[](ptrdiff_t, T*);
7978 void addSubscriptOverloads() {
7979 for (BuiltinCandidateTypeSet::iterator
7980 Ptr = CandidateTypes[0].pointer_begin(),
7981 PtrEnd = CandidateTypes[0].pointer_end();
7982 Ptr != PtrEnd; ++Ptr) {
7983 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7984 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007985 if (!PointeeType->isObjectType())
7986 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007987
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007988 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7989
7990 // T& operator[](T*, ptrdiff_t)
Richard Smithe54c3072013-05-05 15:51:06 +00007991 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007992 }
7993
7994 for (BuiltinCandidateTypeSet::iterator
7995 Ptr = CandidateTypes[1].pointer_begin(),
7996 PtrEnd = CandidateTypes[1].pointer_end();
7997 Ptr != PtrEnd; ++Ptr) {
7998 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7999 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00008000 if (!PointeeType->isObjectType())
8001 continue;
8002
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008003 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
8004
8005 // T& operator[](ptrdiff_t, T*)
Richard Smithe54c3072013-05-05 15:51:06 +00008006 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008007 }
8008 }
8009
8010 // C++ [over.built]p11:
8011 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8012 // C1 is the same type as C2 or is a derived class of C2, T is an object
8013 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8014 // there exist candidate operator functions of the form
8015 //
8016 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8017 //
8018 // where CV12 is the union of CV1 and CV2.
8019 void addArrowStarOverloads() {
8020 for (BuiltinCandidateTypeSet::iterator
8021 Ptr = CandidateTypes[0].pointer_begin(),
8022 PtrEnd = CandidateTypes[0].pointer_end();
8023 Ptr != PtrEnd; ++Ptr) {
8024 QualType C1Ty = (*Ptr);
8025 QualType C1;
8026 QualifierCollector Q1;
8027 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8028 if (!isa<RecordType>(C1))
8029 continue;
8030 // heuristic to reduce number of builtin candidates in the set.
8031 // Add volatile/restrict version only if there are conversions to a
8032 // volatile/restrict type.
8033 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8034 continue;
8035 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8036 continue;
8037 for (BuiltinCandidateTypeSet::iterator
8038 MemPtr = CandidateTypes[1].member_pointer_begin(),
8039 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8040 MemPtr != MemPtrEnd; ++MemPtr) {
8041 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8042 QualType C2 = QualType(mptr->getClass(), 0);
8043 C2 = C2.getUnqualifiedType();
8044 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
8045 break;
8046 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8047 // build CV12 T&
8048 QualType T = mptr->getPointeeType();
8049 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8050 T.isVolatileQualified())
8051 continue;
8052 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8053 T.isRestrictQualified())
8054 continue;
8055 T = Q1.apply(S.Context, T);
8056 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smithe54c3072013-05-05 15:51:06 +00008057 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008058 }
8059 }
8060 }
8061
8062 // Note that we don't consider the first argument, since it has been
8063 // contextually converted to bool long ago. The candidates below are
8064 // therefore added as binary.
8065 //
8066 // C++ [over.built]p25:
8067 // For every type T, where T is a pointer, pointer-to-member, or scoped
8068 // enumeration type, there exist candidate operator functions of the form
8069 //
8070 // T operator?(bool, T, T);
8071 //
8072 void addConditionalOperatorOverloads() {
8073 /// Set of (canonical) types that we've already handled.
8074 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8075
8076 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8077 for (BuiltinCandidateTypeSet::iterator
8078 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8079 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8080 Ptr != PtrEnd; ++Ptr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008081 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008082 continue;
8083
8084 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00008085 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008086 }
8087
8088 for (BuiltinCandidateTypeSet::iterator
8089 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8090 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8091 MemPtr != MemPtrEnd; ++MemPtr) {
David Blaikie82e95a32014-11-19 07:49:47 +00008092 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008093 continue;
8094
8095 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00008096 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008097 }
8098
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008099 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008100 for (BuiltinCandidateTypeSet::iterator
8101 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8102 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8103 Enum != EnumEnd; ++Enum) {
8104 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8105 continue;
8106
David Blaikie82e95a32014-11-19 07:49:47 +00008107 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008108 continue;
8109
8110 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00008111 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008112 }
8113 }
8114 }
8115 }
8116};
8117
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008118} // end anonymous namespace
8119
8120/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8121/// operator overloads to the candidate set (C++ [over.built]), based
8122/// on the operator @p Op and the arguments given. For example, if the
8123/// operator is a binary '+', this routine might add "int
8124/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00008125void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8126 SourceLocation OpLoc,
8127 ArrayRef<Expr *> Args,
8128 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00008129 // Find all of the types that the arguments can convert to, but only
8130 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00008131 // that make use of these types. Also record whether we encounter non-record
8132 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00008133 Qualifiers VisibleTypeConversionsQuals;
8134 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00008135 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00008136 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00008137
8138 bool HasNonRecordCandidateType = false;
8139 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008140 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00008141 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Benjamin Kramer57dddd482015-02-17 21:55:18 +00008142 CandidateTypes.emplace_back(*this);
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008143 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8144 OpLoc,
8145 true,
8146 (Op == OO_Exclaim ||
8147 Op == OO_AmpAmp ||
8148 Op == OO_PipePipe),
8149 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00008150 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8151 CandidateTypes[ArgIdx].hasNonRecordTypes();
8152 HasArithmeticOrEnumeralCandidateType =
8153 HasArithmeticOrEnumeralCandidateType ||
8154 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00008155 }
Douglas Gregora11693b2008-11-12 17:17:38 +00008156
Chandler Carruth00a38332010-12-13 01:44:01 +00008157 // Exit early when no non-record types have been added to the candidate set
8158 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008159 //
8160 // We can't exit early for !, ||, or &&, since there we have always have
8161 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008162 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00008163 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00008164 return;
8165
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008166 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00008167 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008168 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00008169 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008170 CandidateTypes, CandidateSet);
8171
8172 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00008173 switch (Op) {
8174 case OO_None:
8175 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00008176 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00008177
Chandler Carruth5184de02010-12-12 08:51:33 +00008178 case OO_New:
8179 case OO_Delete:
8180 case OO_Array_New:
8181 case OO_Array_Delete:
8182 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00008183 llvm_unreachable(
8184 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00008185
8186 case OO_Comma:
8187 case OO_Arrow:
8188 // C++ [over.match.oper]p3:
8189 // -- For the operator ',', the unary operator '&', or the
8190 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00008191 break;
8192
8193 case OO_Plus: // '+' 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.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00008196 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00008197
8198 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008199 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008200 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008201 } else {
8202 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8203 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8204 }
Douglas Gregord08452f2008-11-19 15:42:04 +00008205 break;
8206
Chandler Carruth5184de02010-12-12 08:51:33 +00008207 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008208 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008209 OpBuilder.addUnaryStarPointerOverloads();
8210 else
8211 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8212 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008213
Chandler Carruth5184de02010-12-12 08:51:33 +00008214 case OO_Slash:
8215 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008216 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008217
8218 case OO_PlusPlus:
8219 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008220 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8221 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008222 break;
8223
Douglas Gregor84605ae2009-08-24 13:43:27 +00008224 case OO_EqualEqual:
8225 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008226 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008227 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008228
Douglas Gregora11693b2008-11-12 17:17:38 +00008229 case OO_Less:
8230 case OO_Greater:
8231 case OO_LessEqual:
8232 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008233 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008234 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8235 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008236
Douglas Gregora11693b2008-11-12 17:17:38 +00008237 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008238 case OO_Caret:
8239 case OO_Pipe:
8240 case OO_LessLess:
8241 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008242 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008243 break;
8244
Chandler Carruth5184de02010-12-12 08:51:33 +00008245 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008246 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008247 // C++ [over.match.oper]p3:
8248 // -- For the operator ',', the unary operator '&', or the
8249 // operator '->', the built-in candidates set is empty.
8250 break;
8251
8252 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8253 break;
8254
8255 case OO_Tilde:
8256 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8257 break;
8258
Douglas Gregora11693b2008-11-12 17:17:38 +00008259 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008260 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008261 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008262
8263 case OO_PlusEqual:
8264 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008265 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008266 // Fall through.
8267
8268 case OO_StarEqual:
8269 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008270 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008271 break;
8272
8273 case OO_PercentEqual:
8274 case OO_LessLessEqual:
8275 case OO_GreaterGreaterEqual:
8276 case OO_AmpEqual:
8277 case OO_CaretEqual:
8278 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008279 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008280 break;
8281
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008282 case OO_Exclaim:
8283 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008284 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008285
Douglas Gregora11693b2008-11-12 17:17:38 +00008286 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008287 case OO_PipePipe:
8288 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008289 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008290
8291 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008292 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008293 break;
8294
8295 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008296 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008297 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008298
8299 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008300 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008301 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8302 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008303 }
8304}
8305
Douglas Gregore254f902009-02-04 00:32:51 +00008306/// \brief Add function candidates found via argument-dependent lookup
8307/// to the set of overloading candidates.
8308///
8309/// This routine performs argument-dependent name lookup based on the
8310/// given function name (which may also be an operator name) and adds
8311/// all of the overload candidates found by ADL to the overload
8312/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008313void
Douglas Gregore254f902009-02-04 00:32:51 +00008314Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smith100b24a2014-04-17 01:52:14 +00008315 SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008316 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008317 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008318 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008319 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008320 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008321
John McCall91f61fc2010-01-26 06:04:06 +00008322 // FIXME: This approach for uniquing ADL results (and removing
8323 // redundant candidates from the set) relies on pointer-equality,
8324 // which means we need to key off the canonical decl. However,
8325 // always going back to the canonical decl might not get us the
8326 // right set of default arguments. What default arguments are
8327 // we supposed to consider on ADL candidates, anyway?
8328
Douglas Gregorcabea402009-09-22 15:41:20 +00008329 // FIXME: Pass in the explicit template arguments?
Richard Smith100b24a2014-04-17 01:52:14 +00008330 ArgumentDependentLookup(Name, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008331
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008332 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008333 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8334 CandEnd = CandidateSet.end();
8335 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008336 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008337 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008338 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008339 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008340 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008341
8342 // For each of the ADL candidates we found, add it to the overload
8343 // set.
John McCall8fe68082010-01-26 07:16:45 +00008344 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008345 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008346 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008347 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008348 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008349
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008350 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8351 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008352 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008353 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008354 FoundDecl, ExplicitTemplateArgs,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +00008355 Args, CandidateSet, PartialOverloading);
Douglas Gregor15448f82009-06-27 21:05:07 +00008356 }
Douglas Gregore254f902009-02-04 00:32:51 +00008357}
8358
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008359/// isBetterOverloadCandidate - Determines whether the first overload
8360/// candidate is a better candidate than the second (C++ 13.3.3p1).
Richard Smith17c00b42014-11-12 01:24:00 +00008361bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1,
8362 const OverloadCandidate &Cand2,
8363 SourceLocation Loc,
8364 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008365 // Define viable functions to be better candidates than non-viable
8366 // functions.
8367 if (!Cand2.Viable)
8368 return Cand1.Viable;
8369 else if (!Cand1.Viable)
8370 return false;
8371
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008372 // C++ [over.match.best]p1:
8373 //
8374 // -- if F is a static member function, ICS1(F) is defined such
8375 // that ICS1(F) is neither better nor worse than ICS1(G) for
8376 // any function G, and, symmetrically, ICS1(G) is neither
8377 // better nor worse than ICS1(F).
8378 unsigned StartArg = 0;
8379 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8380 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008381
Douglas Gregord3cb3562009-07-07 23:38:56 +00008382 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008383 // A viable function F1 is defined to be a better function than another
8384 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008385 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00008386 unsigned NumArgs = Cand1.NumConversions;
8387 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008388 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008389 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00008390 switch (CompareImplicitConversionSequences(S,
8391 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008392 Cand2.Conversions[ArgIdx])) {
8393 case ImplicitConversionSequence::Better:
8394 // Cand1 has a better conversion sequence.
8395 HasBetterConversion = true;
8396 break;
8397
8398 case ImplicitConversionSequence::Worse:
8399 // Cand1 can't be better than Cand2.
8400 return false;
8401
8402 case ImplicitConversionSequence::Indistinguishable:
8403 // Do nothing.
8404 break;
8405 }
8406 }
8407
Mike Stump11289f42009-09-09 15:08:12 +00008408 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008409 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008410 if (HasBetterConversion)
8411 return true;
8412
Douglas Gregora1f013e2008-11-07 22:36:19 +00008413 // -- the context is an initialization by user-defined conversion
8414 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8415 // from the return type of F1 to the destination type (i.e.,
8416 // the type of the entity being initialized) is a better
8417 // conversion sequence than the standard conversion sequence
8418 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00008419 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00008420 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00008421 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00008422 // First check whether we prefer one of the conversion functions over the
8423 // other. This only distinguishes the results in non-standard, extension
8424 // cases such as the conversion from a lambda closure type to a function
8425 // pointer or block.
Richard Smithec2748a2014-05-17 04:36:39 +00008426 ImplicitConversionSequence::CompareKind Result =
8427 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8428 if (Result == ImplicitConversionSequence::Indistinguishable)
8429 Result = CompareStandardConversionSequences(S,
8430 Cand1.FinalConversion,
8431 Cand2.FinalConversion);
Richard Smith6fdeaab2014-05-17 01:58:45 +00008432
Richard Smithec2748a2014-05-17 04:36:39 +00008433 if (Result != ImplicitConversionSequence::Indistinguishable)
8434 return Result == ImplicitConversionSequence::Better;
Richard Smith6fdeaab2014-05-17 01:58:45 +00008435
8436 // FIXME: Compare kind of reference binding if conversion functions
8437 // convert to a reference type used in direct reference binding, per
8438 // C++14 [over.match.best]p1 section 2 bullet 3.
8439 }
8440
8441 // -- F1 is a non-template function and F2 is a function template
8442 // specialization, or, if not that,
8443 bool Cand1IsSpecialization = Cand1.Function &&
8444 Cand1.Function->getPrimaryTemplate();
8445 bool Cand2IsSpecialization = Cand2.Function &&
8446 Cand2.Function->getPrimaryTemplate();
8447 if (Cand1IsSpecialization != Cand2IsSpecialization)
8448 return Cand2IsSpecialization;
8449
8450 // -- F1 and F2 are function template specializations, and the function
8451 // template for F1 is more specialized than the template for F2
8452 // according to the partial ordering rules described in 14.5.5.2, or,
8453 // if not that,
8454 if (Cand1IsSpecialization && Cand2IsSpecialization) {
8455 if (FunctionTemplateDecl *BetterTemplate
8456 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8457 Cand2.Function->getPrimaryTemplate(),
8458 Loc,
8459 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8460 : TPOC_Call,
8461 Cand1.ExplicitCallArguments,
8462 Cand2.ExplicitCallArguments))
8463 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregora1f013e2008-11-07 22:36:19 +00008464 }
8465
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008466 // Check for enable_if value-based overload resolution.
8467 if (Cand1.Function && Cand2.Function &&
8468 (Cand1.Function->hasAttr<EnableIfAttr>() ||
8469 Cand2.Function->hasAttr<EnableIfAttr>())) {
8470 // FIXME: The next several lines are just
8471 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8472 // instead of reverse order which is how they're stored in the AST.
8473 AttrVec Cand1Attrs;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008474 if (Cand1.Function->hasAttrs()) {
8475 Cand1Attrs = Cand1.Function->getAttrs();
Richard Smith9516eee2014-05-17 02:21:47 +00008476 Cand1Attrs.erase(std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(),
8477 IsNotEnableIfAttr),
8478 Cand1Attrs.end());
8479 std::reverse(Cand1Attrs.begin(), Cand1Attrs.end());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008480 }
8481
8482 AttrVec Cand2Attrs;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008483 if (Cand2.Function->hasAttrs()) {
8484 Cand2Attrs = Cand2.Function->getAttrs();
Richard Smith9516eee2014-05-17 02:21:47 +00008485 Cand2Attrs.erase(std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(),
8486 IsNotEnableIfAttr),
8487 Cand2Attrs.end());
8488 std::reverse(Cand2Attrs.begin(), Cand2Attrs.end());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008489 }
Richard Smith9516eee2014-05-17 02:21:47 +00008490
8491 // Candidate 1 is better if it has strictly more attributes and
8492 // the common sequence is identical.
8493 if (Cand1Attrs.size() <= Cand2Attrs.size())
8494 return false;
8495
8496 auto Cand1I = Cand1Attrs.begin();
8497 for (auto &Cand2A : Cand2Attrs) {
8498 auto &Cand1A = *Cand1I++;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008499 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
Richard Smith9516eee2014-05-17 02:21:47 +00008500 cast<EnableIfAttr>(Cand1A)->getCond()->Profile(Cand1ID,
8501 S.getASTContext(), true);
8502 cast<EnableIfAttr>(Cand2A)->getCond()->Profile(Cand2ID,
8503 S.getASTContext(), true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00008504 if (Cand1ID != Cand2ID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008505 return false;
8506 }
Richard Smith9516eee2014-05-17 02:21:47 +00008507
8508 return true;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008509 }
8510
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008511 return false;
8512}
8513
Mike Stump11289f42009-09-09 15:08:12 +00008514/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008515/// within an overload candidate set.
8516///
James Dennettffad8b72012-06-22 08:10:18 +00008517/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008518/// which overload resolution occurs.
8519///
James Dennettffad8b72012-06-22 08:10:18 +00008520/// \param Best If overload resolution was successful or found a deleted
8521/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008522///
8523/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00008524OverloadingResult
8525OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008526 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00008527 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008528 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00008529 Best = end();
8530 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8531 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008532 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008533 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008534 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008535 }
8536
8537 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00008538 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008539 return OR_No_Viable_Function;
8540
8541 // Make sure that this function is better than every other viable
8542 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00008543 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00008544 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008545 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008546 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008547 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00008548 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008549 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00008550 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008551 }
Mike Stump11289f42009-09-09 15:08:12 +00008552
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008553 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00008554 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008555 (Best->Function->isDeleted() ||
8556 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00008557 return OR_Deleted;
8558
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008559 return OR_Success;
8560}
8561
John McCall53262c92010-01-12 02:15:36 +00008562namespace {
8563
8564enum OverloadCandidateKind {
8565 oc_function,
8566 oc_method,
8567 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00008568 oc_function_template,
8569 oc_method_template,
8570 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00008571 oc_implicit_default_constructor,
8572 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008573 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00008574 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008575 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00008576 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00008577};
8578
John McCalle1ac8d12010-01-13 00:25:19 +00008579OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8580 FunctionDecl *Fn,
8581 std::string &Description) {
8582 bool isTemplate = false;
8583
8584 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8585 isTemplate = true;
8586 Description = S.getTemplateArgumentBindingsText(
8587 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8588 }
John McCallfd0b2f82010-01-06 09:43:14 +00008589
8590 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00008591 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008592 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008593
Sebastian Redl08905022011-02-05 19:23:19 +00008594 if (Ctor->getInheritedConstructor())
8595 return oc_implicit_inherited_constructor;
8596
Alexis Hunt119c10e2011-05-25 23:16:36 +00008597 if (Ctor->isDefaultConstructor())
8598 return oc_implicit_default_constructor;
8599
8600 if (Ctor->isMoveConstructor())
8601 return oc_implicit_move_constructor;
8602
8603 assert(Ctor->isCopyConstructor() &&
8604 "unexpected sort of implicit constructor");
8605 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008606 }
8607
8608 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8609 // This actually gets spelled 'candidate function' for now, but
8610 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00008611 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008612 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00008613
Alexis Hunt119c10e2011-05-25 23:16:36 +00008614 if (Meth->isMoveAssignmentOperator())
8615 return oc_implicit_move_assignment;
8616
Douglas Gregor12695102012-02-10 08:36:38 +00008617 if (Meth->isCopyAssignmentOperator())
8618 return oc_implicit_copy_assignment;
8619
8620 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8621 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00008622 }
8623
John McCalle1ac8d12010-01-13 00:25:19 +00008624 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00008625}
8626
Larisse Voufo98b20f12013-07-19 23:00:19 +00008627void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
Sebastian Redl08905022011-02-05 19:23:19 +00008628 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8629 if (!Ctor) return;
8630
8631 Ctor = Ctor->getInheritedConstructor();
8632 if (!Ctor) return;
8633
8634 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8635}
8636
John McCall53262c92010-01-12 02:15:36 +00008637} // end anonymous namespace
8638
8639// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00008640void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00008641 std::string FnDesc;
8642 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00008643 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8644 << (unsigned) K << FnDesc;
8645 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8646 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00008647 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00008648}
8649
Nick Lewyckyed4265c2013-09-22 10:06:01 +00008650// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00008651// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00008652void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008653 assert(OverloadedExpr->getType() == Context.OverloadTy);
8654
8655 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8656 OverloadExpr *OvlExpr = Ovl.Expression;
8657
8658 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8659 IEnd = OvlExpr->decls_end();
8660 I != IEnd; ++I) {
8661 if (FunctionTemplateDecl *FunTmpl =
8662 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00008663 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008664 } else if (FunctionDecl *Fun
8665 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00008666 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008667 }
8668 }
8669}
8670
John McCall0d1da222010-01-12 00:44:57 +00008671/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8672/// "lead" diagnostic; it will be given two arguments, the source and
8673/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00008674void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8675 Sema &S,
8676 SourceLocation CaretLoc,
8677 const PartialDiagnostic &PDiag) const {
8678 S.Diag(CaretLoc, PDiag)
8679 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008680 // FIXME: The note limiting machinery is borrowed from
8681 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8682 // refactoring here.
8683 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8684 unsigned CandsShown = 0;
8685 AmbiguousConversionSequence::const_iterator I, E;
8686 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8687 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8688 break;
8689 ++CandsShown;
John McCall5c32be02010-08-24 20:38:10 +00008690 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00008691 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008692 if (I != E)
8693 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00008694}
8695
Richard Smith17c00b42014-11-12 01:24:00 +00008696static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
8697 unsigned I) {
John McCall6a61b522010-01-13 09:16:55 +00008698 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8699 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00008700 assert(Cand->Function && "for now, candidate must be a function");
8701 FunctionDecl *Fn = Cand->Function;
8702
8703 // There's a conversion slot for the object argument if this is a
8704 // non-constructor method. Note that 'I' corresponds the
8705 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00008706 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00008707 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00008708 if (I == 0)
8709 isObjectArgument = true;
8710 else
8711 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00008712 }
8713
John McCalle1ac8d12010-01-13 00:25:19 +00008714 std::string FnDesc;
8715 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8716
John McCall6a61b522010-01-13 09:16:55 +00008717 Expr *FromExpr = Conv.Bad.FromExpr;
8718 QualType FromTy = Conv.Bad.getFromType();
8719 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00008720
John McCallfb7ad0f2010-02-02 02:42:52 +00008721 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00008722 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00008723 Expr *E = FromExpr->IgnoreParens();
8724 if (isa<UnaryOperator>(E))
8725 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00008726 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00008727
8728 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8729 << (unsigned) FnKind << FnDesc
8730 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8731 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008732 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00008733 return;
8734 }
8735
John McCall6d174642010-01-23 08:10:49 +00008736 // Do some hand-waving analysis to see if the non-viability is due
8737 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00008738 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8739 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8740 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8741 CToTy = RT->getPointeeType();
8742 else {
8743 // TODO: detect and diagnose the full richness of const mismatches.
8744 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8745 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8746 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8747 }
8748
8749 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8750 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00008751 Qualifiers FromQs = CFromTy.getQualifiers();
8752 Qualifiers ToQs = CToTy.getQualifiers();
8753
8754 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8755 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8756 << (unsigned) FnKind << FnDesc
8757 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8758 << FromTy
8759 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8760 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008761 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008762 return;
8763 }
8764
John McCall31168b02011-06-15 23:02:42 +00008765 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008766 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00008767 << (unsigned) FnKind << FnDesc
8768 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8769 << FromTy
8770 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8771 << (unsigned) isObjectArgument << I+1;
8772 MaybeEmitInheritedConstructorNote(S, Fn);
8773 return;
8774 }
8775
Douglas Gregoraec25842011-04-26 23:16:46 +00008776 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8777 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8778 << (unsigned) FnKind << FnDesc
8779 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8780 << FromTy
8781 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8782 << (unsigned) isObjectArgument << I+1;
8783 MaybeEmitInheritedConstructorNote(S, Fn);
8784 return;
8785 }
8786
John McCall47000992010-01-14 03:28:57 +00008787 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8788 assert(CVR && "unexpected qualifiers mismatch");
8789
8790 if (isObjectArgument) {
8791 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8792 << (unsigned) FnKind << FnDesc
8793 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8794 << FromTy << (CVR - 1);
8795 } else {
8796 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8797 << (unsigned) FnKind << FnDesc
8798 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8799 << FromTy << (CVR - 1) << I+1;
8800 }
Sebastian Redl08905022011-02-05 19:23:19 +00008801 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008802 return;
8803 }
8804
Sebastian Redla72462c2011-09-24 17:48:32 +00008805 // Special diagnostic for failure to convert an initializer list, since
8806 // telling the user that it has type void is not useful.
8807 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8808 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8809 << (unsigned) FnKind << FnDesc
8810 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8811 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8812 MaybeEmitInheritedConstructorNote(S, Fn);
8813 return;
8814 }
8815
John McCall6d174642010-01-23 08:10:49 +00008816 // Diagnose references or pointers to incomplete types differently,
8817 // since it's far from impossible that the incompleteness triggered
8818 // the failure.
8819 QualType TempFromTy = FromTy.getNonReferenceType();
8820 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8821 TempFromTy = PTy->getPointeeType();
8822 if (TempFromTy->isIncompleteType()) {
8823 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8824 << (unsigned) FnKind << FnDesc
8825 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8826 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008827 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00008828 return;
8829 }
8830
Douglas Gregor56f2e342010-06-30 23:01:39 +00008831 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008832 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008833 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8834 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8835 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8836 FromPtrTy->getPointeeType()) &&
8837 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8838 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008839 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00008840 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008841 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008842 }
8843 } else if (const ObjCObjectPointerType *FromPtrTy
8844 = FromTy->getAs<ObjCObjectPointerType>()) {
8845 if (const ObjCObjectPointerType *ToPtrTy
8846 = ToTy->getAs<ObjCObjectPointerType>())
8847 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8848 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8849 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8850 FromPtrTy->getPointeeType()) &&
8851 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008852 BaseToDerivedConversion = 2;
8853 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008854 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8855 !FromTy->isIncompleteType() &&
8856 !ToRefTy->getPointeeType()->isIncompleteType() &&
8857 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8858 BaseToDerivedConversion = 3;
8859 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8860 ToTy.getNonReferenceType().getCanonicalType() ==
8861 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008862 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8863 << (unsigned) FnKind << FnDesc
8864 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8865 << (unsigned) isObjectArgument << I + 1;
8866 MaybeEmitInheritedConstructorNote(S, Fn);
8867 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008868 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008869 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008870
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008871 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008872 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008873 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00008874 << (unsigned) FnKind << FnDesc
8875 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008876 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008877 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008878 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00008879 return;
8880 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008881
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00008882 if (isa<ObjCObjectPointerType>(CFromTy) &&
8883 isa<PointerType>(CToTy)) {
8884 Qualifiers FromQs = CFromTy.getQualifiers();
8885 Qualifiers ToQs = CToTy.getQualifiers();
8886 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8887 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8888 << (unsigned) FnKind << FnDesc
8889 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8890 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8891 MaybeEmitInheritedConstructorNote(S, Fn);
8892 return;
8893 }
8894 }
8895
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008896 // Emit the generic diagnostic and, optionally, add the hints to it.
8897 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8898 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00008899 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008900 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8901 << (unsigned) (Cand->Fix.Kind);
8902
8903 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00008904 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8905 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008906 FDiag << *HI;
8907 S.Diag(Fn->getLocation(), FDiag);
8908
Sebastian Redl08905022011-02-05 19:23:19 +00008909 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00008910}
8911
Larisse Voufo98b20f12013-07-19 23:00:19 +00008912/// Additional arity mismatch diagnosis specific to a function overload
8913/// candidates. This is not covered by the more general DiagnoseArityMismatch()
8914/// over a candidate in any candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00008915static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8916 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00008917 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00008918 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008919
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008920 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00008921 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008922 // right number of arguments, because only overloaded operators have
8923 // the weird behavior of overloading member and non-member functions.
8924 // Just don't report anything.
8925 if (Fn->isInvalidDecl() &&
8926 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008927 return true;
8928
8929 if (NumArgs < MinParams) {
8930 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8931 (Cand->FailureKind == ovl_fail_bad_deduction &&
8932 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8933 } else {
8934 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8935 (Cand->FailureKind == ovl_fail_bad_deduction &&
8936 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8937 }
8938
8939 return false;
8940}
8941
8942/// General arity mismatch diagnosis over a candidate in a candidate set.
Richard Smith17c00b42014-11-12 01:24:00 +00008943static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008944 assert(isa<FunctionDecl>(D) &&
8945 "The templated declaration should at least be a function"
8946 " when diagnosing bad template argument deduction due to too many"
8947 " or too few arguments");
8948
8949 FunctionDecl *Fn = cast<FunctionDecl>(D);
8950
8951 // TODO: treat calls to a missing default constructor as a special case
8952 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8953 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008954
John McCall6a61b522010-01-13 09:16:55 +00008955 // at least / at most / exactly
8956 unsigned mode, modeCount;
8957 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00008958 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
8959 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00008960 mode = 0; // "at least"
8961 else
8962 mode = 2; // "exactly"
8963 modeCount = MinParams;
8964 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00008965 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00008966 mode = 1; // "at most"
8967 else
8968 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00008969 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00008970 }
8971
8972 std::string Description;
8973 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8974
Richard Smith10ff50d2012-05-11 05:16:41 +00008975 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8976 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
Craig Topperc3ec1492014-05-26 06:22:03 +00008977 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8978 << mode << Fn->getParamDecl(0) << NumFormalArgs;
Richard Smith10ff50d2012-05-11 05:16:41 +00008979 else
8980 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Craig Topperc3ec1492014-05-26 06:22:03 +00008981 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8982 << mode << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00008983 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008984}
8985
Larisse Voufo98b20f12013-07-19 23:00:19 +00008986/// Arity mismatch diagnosis specific to a function overload candidate.
Richard Smith17c00b42014-11-12 01:24:00 +00008987static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8988 unsigned NumFormalArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008989 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
8990 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
8991}
Larisse Voufo47c08452013-07-19 22:53:23 +00008992
Richard Smith17c00b42014-11-12 01:24:00 +00008993static TemplateDecl *getDescribedTemplate(Decl *Templated) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008994 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
8995 return FD->getDescribedFunctionTemplate();
8996 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
8997 return RD->getDescribedClassTemplate();
8998
8999 llvm_unreachable("Unsupported: Getting the described template declaration"
9000 " for bad deduction diagnosis");
9001}
9002
9003/// Diagnose a failed template-argument deduction.
Richard Smith17c00b42014-11-12 01:24:00 +00009004static void DiagnoseBadDeduction(Sema &S, Decl *Templated,
9005 DeductionFailureInfo &DeductionFailure,
9006 unsigned NumArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009007 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009008 NamedDecl *ParamD;
9009 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
9010 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
9011 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00009012 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00009013 case Sema::TDK_Success:
9014 llvm_unreachable("TDK_success while diagnosing bad deduction");
9015
9016 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00009017 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00009018 S.Diag(Templated->getLocation(),
9019 diag::note_ovl_candidate_incomplete_deduction)
9020 << ParamD->getDeclName();
9021 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00009022 return;
9023 }
9024
John McCall42d7d192010-08-05 09:05:08 +00009025 case Sema::TDK_Underqualified: {
9026 assert(ParamD && "no parameter found for bad qualifiers deduction result");
9027 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
9028
Larisse Voufo98b20f12013-07-19 23:00:19 +00009029 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009030
9031 // Param will have been canonicalized, but it should just be a
9032 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00009033 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00009034 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00009035 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00009036 assert(S.Context.hasSameType(Param, NonCanonParam));
9037
9038 // Arg has also been canonicalized, but there's nothing we can do
9039 // about that. It also doesn't matter as much, because it won't
9040 // have any template parameters in it (because deduction isn't
9041 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00009042 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00009043
Larisse Voufo98b20f12013-07-19 23:00:19 +00009044 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
9045 << ParamD->getDeclName() << Arg << NonCanonParam;
9046 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall42d7d192010-08-05 09:05:08 +00009047 return;
9048 }
9049
9050 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009051 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009052 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009053 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009054 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009055 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009056 which = 1;
9057 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009058 which = 2;
9059 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009060
Larisse Voufo98b20f12013-07-19 23:00:19 +00009061 S.Diag(Templated->getLocation(),
9062 diag::note_ovl_candidate_inconsistent_deduction)
9063 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
9064 << *DeductionFailure.getSecondArg();
9065 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00009066 return;
9067 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00009068
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009069 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009070 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009071 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00009072 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009073 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009074 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009075 else {
9076 int index = 0;
9077 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
9078 index = TTP->getIndex();
9079 else if (NonTypeTemplateParmDecl *NTTP
9080 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
9081 index = NTTP->getIndex();
9082 else
9083 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00009084 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009085 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009086 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009087 }
Larisse Voufo98b20f12013-07-19 23:00:19 +00009088 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00009089 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009090
Douglas Gregor02eb4832010-05-08 18:13:28 +00009091 case Sema::TDK_TooManyArguments:
9092 case Sema::TDK_TooFewArguments:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009093 DiagnoseArityMismatch(S, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00009094 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00009095
9096 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009097 S.Diag(Templated->getLocation(),
9098 diag::note_ovl_candidate_instantiation_depth);
9099 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00009100 return;
9101
9102 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00009103 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009104 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009105 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00009106 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00009107 TemplateArgString = " ";
9108 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00009109 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00009110 }
9111
Richard Smith6f8d2c62012-05-09 05:17:00 +00009112 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009113 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00009114 if (PDiag && PDiag->second.getDiagID() ==
9115 diag::err_typename_nested_not_found_enable_if) {
9116 // FIXME: Use the source range of the condition, and the fully-qualified
9117 // name of the enable_if template. These are both present in PDiag.
9118 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
9119 << "'enable_if'" << TemplateArgString;
9120 return;
9121 }
9122
Richard Smith9ca64612012-05-07 09:03:25 +00009123 // Format the SFINAE diagnostic into the argument string.
9124 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
9125 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009126 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00009127 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00009128 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00009129 SFINAEArgString = ": ";
9130 R = SourceRange(PDiag->first, PDiag->first);
9131 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
9132 }
9133
Larisse Voufo98b20f12013-07-19 23:00:19 +00009134 S.Diag(Templated->getLocation(),
9135 diag::note_ovl_candidate_substitution_failure)
9136 << TemplateArgString << SFINAEArgString << R;
9137 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00009138 return;
9139 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009140
Richard Smith8c6eeb92013-01-31 04:03:12 +00009141 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009142 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
9143 S.Diag(Templated->getLocation(),
Richard Smith8c6eeb92013-01-31 04:03:12 +00009144 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo98b20f12013-07-19 23:00:19 +00009145 << R.Expression->getName();
Richard Smith8c6eeb92013-01-31 04:03:12 +00009146 return;
9147 }
9148
Richard Trieue3732352013-04-08 21:11:40 +00009149 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00009150 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009151 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
9152 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00009153 if (FirstTA.getKind() == TemplateArgument::Template &&
9154 SecondTA.getKind() == TemplateArgument::Template) {
9155 TemplateName FirstTN = FirstTA.getAsTemplate();
9156 TemplateName SecondTN = SecondTA.getAsTemplate();
9157 if (FirstTN.getKind() == TemplateName::Template &&
9158 SecondTN.getKind() == TemplateName::Template) {
9159 if (FirstTN.getAsTemplateDecl()->getName() ==
9160 SecondTN.getAsTemplateDecl()->getName()) {
9161 // FIXME: This fixes a bad diagnostic where both templates are named
9162 // the same. This particular case is a bit difficult since:
9163 // 1) It is passed as a string to the diagnostic printer.
9164 // 2) The diagnostic printer only attempts to find a better
9165 // name for types, not decls.
9166 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009167 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +00009168 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
9169 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9170 return;
9171 }
9172 }
9173 }
Faisal Vali2b391ab2013-09-26 19:54:12 +00009174 // FIXME: For generic lambda parameters, check if the function is a lambda
9175 // call operator, and if so, emit a prettier and more informative
9176 // diagnostic that mentions 'auto' and lambda in addition to
9177 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +00009178 S.Diag(Templated->getLocation(),
9179 diag::note_ovl_candidate_non_deduced_mismatch)
9180 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +00009181 return;
Richard Trieue3732352013-04-08 21:11:40 +00009182 }
John McCall8b9ed552010-02-01 18:53:26 +00009183 // TODO: diagnose these individually, then kill off
9184 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +00009185 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009186 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9187 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00009188 return;
9189 }
9190}
9191
Larisse Voufo98b20f12013-07-19 23:00:19 +00009192/// Diagnose a failed template-argument deduction, for function calls.
Richard Smith17c00b42014-11-12 01:24:00 +00009193static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
9194 unsigned NumArgs) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009195 unsigned TDK = Cand->DeductionFailure.Result;
9196 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9197 if (CheckArityMismatch(S, Cand, NumArgs))
9198 return;
9199 }
9200 DiagnoseBadDeduction(S, Cand->Function, // pattern
9201 Cand->DeductionFailure, NumArgs);
9202}
9203
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009204/// CUDA: diagnose an invalid call across targets.
Richard Smith17c00b42014-11-12 01:24:00 +00009205static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009206 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9207 FunctionDecl *Callee = Cand->Function;
9208
9209 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9210 CalleeTarget = S.IdentifyCUDATarget(Callee);
9211
9212 std::string FnDesc;
9213 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
9214
9215 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
Eli Bendersky9a220fc2014-09-29 20:38:29 +00009216 << (unsigned)FnKind << CalleeTarget << CallerTarget;
9217
9218 // This could be an implicit constructor for which we could not infer the
9219 // target due to a collsion. Diagnose that case.
9220 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
9221 if (Meth != nullptr && Meth->isImplicit()) {
9222 CXXRecordDecl *ParentClass = Meth->getParent();
9223 Sema::CXXSpecialMember CSM;
9224
9225 switch (FnKind) {
9226 default:
9227 return;
9228 case oc_implicit_default_constructor:
9229 CSM = Sema::CXXDefaultConstructor;
9230 break;
9231 case oc_implicit_copy_constructor:
9232 CSM = Sema::CXXCopyConstructor;
9233 break;
9234 case oc_implicit_move_constructor:
9235 CSM = Sema::CXXMoveConstructor;
9236 break;
9237 case oc_implicit_copy_assignment:
9238 CSM = Sema::CXXCopyAssignment;
9239 break;
9240 case oc_implicit_move_assignment:
9241 CSM = Sema::CXXMoveAssignment;
9242 break;
9243 };
9244
9245 bool ConstRHS = false;
9246 if (Meth->getNumParams()) {
9247 if (const ReferenceType *RT =
9248 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
9249 ConstRHS = RT->getPointeeType().isConstQualified();
9250 }
9251 }
9252
9253 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
9254 /* ConstRHS */ ConstRHS,
9255 /* Diagnose */ true);
9256 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009257}
9258
Richard Smith17c00b42014-11-12 01:24:00 +00009259static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009260 FunctionDecl *Callee = Cand->Function;
9261 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9262
9263 S.Diag(Callee->getLocation(),
9264 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9265 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9266}
9267
John McCall8b9ed552010-02-01 18:53:26 +00009268/// Generates a 'note' diagnostic for an overload candidate. We've
9269/// already generated a primary error at the call site.
9270///
9271/// It really does need to be a single diagnostic with its caret
9272/// pointed at the candidate declaration. Yes, this creates some
9273/// major challenges of technical writing. Yes, this makes pointing
9274/// out problems with specific arguments quite awkward. It's still
9275/// better than generating twenty screens of text for every failed
9276/// overload.
9277///
9278/// It would be great to be able to express per-candidate problems
9279/// more richly for those diagnostic clients that cared, but we'd
9280/// still have to be just as careful with the default diagnostics.
Richard Smith17c00b42014-11-12 01:24:00 +00009281static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
9282 unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00009283 FunctionDecl *Fn = Cand->Function;
9284
John McCall12f97bc2010-01-08 04:41:39 +00009285 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009286 if (Cand->Viable && (Fn->isDeleted() ||
9287 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00009288 std::string FnDesc;
9289 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00009290
9291 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00009292 << FnKind << FnDesc
9293 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redl08905022011-02-05 19:23:19 +00009294 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00009295 return;
John McCall12f97bc2010-01-08 04:41:39 +00009296 }
9297
John McCalle1ac8d12010-01-13 00:25:19 +00009298 // We don't really have anything else to say about viable candidates.
9299 if (Cand->Viable) {
9300 S.NoteOverloadCandidate(Fn);
9301 return;
9302 }
John McCall0d1da222010-01-12 00:44:57 +00009303
John McCall6a61b522010-01-13 09:16:55 +00009304 switch (Cand->FailureKind) {
9305 case ovl_fail_too_many_arguments:
9306 case ovl_fail_too_few_arguments:
9307 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00009308
John McCall6a61b522010-01-13 09:16:55 +00009309 case ovl_fail_bad_deduction:
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009310 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall8b9ed552010-02-01 18:53:26 +00009311
John McCall578a1f82014-12-14 01:46:53 +00009312 case ovl_fail_illegal_constructor: {
9313 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
9314 << (Fn->getPrimaryTemplate() ? 1 : 0);
9315 MaybeEmitInheritedConstructorNote(S, Fn);
9316 return;
9317 }
9318
John McCallfe796dd2010-01-23 05:17:32 +00009319 case ovl_fail_trivial_conversion:
9320 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00009321 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00009322 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009323
John McCall65eb8792010-02-25 01:37:24 +00009324 case ovl_fail_bad_conversion: {
9325 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009326 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00009327 if (Cand->Conversions[I].isBad())
9328 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009329
John McCall6a61b522010-01-13 09:16:55 +00009330 // FIXME: this currently happens when we're called from SemaInit
9331 // when user-conversion overload fails. Figure out how to handle
9332 // those conditions and diagnose them well.
9333 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009334 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009335
9336 case ovl_fail_bad_target:
9337 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009338
9339 case ovl_fail_enable_if:
9340 return DiagnoseFailedEnableIfAttr(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00009341 }
John McCalld3224162010-01-08 00:58:21 +00009342}
9343
Richard Smith17c00b42014-11-12 01:24:00 +00009344static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
John McCalld3224162010-01-08 00:58:21 +00009345 // Desugar the type of the surrogate down to a function type,
9346 // retaining as many typedefs as possible while still showing
9347 // the function type (and, therefore, its parameter types).
9348 QualType FnType = Cand->Surrogate->getConversionType();
9349 bool isLValueReference = false;
9350 bool isRValueReference = false;
9351 bool isPointer = false;
9352 if (const LValueReferenceType *FnTypeRef =
9353 FnType->getAs<LValueReferenceType>()) {
9354 FnType = FnTypeRef->getPointeeType();
9355 isLValueReference = true;
9356 } else if (const RValueReferenceType *FnTypeRef =
9357 FnType->getAs<RValueReferenceType>()) {
9358 FnType = FnTypeRef->getPointeeType();
9359 isRValueReference = true;
9360 }
9361 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9362 FnType = FnTypePtr->getPointeeType();
9363 isPointer = true;
9364 }
9365 // Desugar down to a function type.
9366 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9367 // Reconstruct the pointer/reference as appropriate.
9368 if (isPointer) FnType = S.Context.getPointerType(FnType);
9369 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9370 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9371
9372 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9373 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00009374 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00009375}
9376
Richard Smith17c00b42014-11-12 01:24:00 +00009377static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
9378 SourceLocation OpLoc,
9379 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009380 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00009381 std::string TypeStr("operator");
9382 TypeStr += Opc;
9383 TypeStr += "(";
9384 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00009385 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00009386 TypeStr += ")";
9387 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9388 } else {
9389 TypeStr += ", ";
9390 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9391 TypeStr += ")";
9392 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9393 }
9394}
9395
Richard Smith17c00b42014-11-12 01:24:00 +00009396static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9397 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009398 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00009399 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9400 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00009401 if (ICS.isBad()) break; // all meaningless after first invalid
9402 if (!ICS.isAmbiguous()) continue;
9403
John McCall5c32be02010-08-24 20:38:10 +00009404 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00009405 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00009406 }
9407}
9408
Larisse Voufo98b20f12013-07-19 23:00:19 +00009409static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +00009410 if (Cand->Function)
9411 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00009412 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00009413 return Cand->Surrogate->getLocation();
9414 return SourceLocation();
9415}
9416
Larisse Voufo98b20f12013-07-19 23:00:19 +00009417static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00009418 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009419 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00009420 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009421
Douglas Gregorc5c01a62012-09-13 21:01:57 +00009422 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009423 case Sema::TDK_Incomplete:
9424 return 1;
9425
9426 case Sema::TDK_Underqualified:
9427 case Sema::TDK_Inconsistent:
9428 return 2;
9429
9430 case Sema::TDK_SubstitutionFailure:
9431 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +00009432 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009433 return 3;
9434
9435 case Sema::TDK_InstantiationDepth:
9436 case Sema::TDK_FailedOverloadResolution:
9437 return 4;
9438
9439 case Sema::TDK_InvalidExplicitArguments:
9440 return 5;
9441
9442 case Sema::TDK_TooManyArguments:
9443 case Sema::TDK_TooFewArguments:
9444 return 6;
9445 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009446 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009447}
9448
Richard Smith17c00b42014-11-12 01:24:00 +00009449namespace {
John McCallad2587a2010-01-12 00:48:53 +00009450struct CompareOverloadCandidatesForDisplay {
9451 Sema &S;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009452 size_t NumArgs;
9453
9454 CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs)
9455 : S(S), NumArgs(nArgs) {}
John McCall12f97bc2010-01-08 04:41:39 +00009456
9457 bool operator()(const OverloadCandidate *L,
9458 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00009459 // Fast-path this check.
9460 if (L == R) return false;
9461
John McCall12f97bc2010-01-08 04:41:39 +00009462 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00009463 if (L->Viable) {
9464 if (!R->Viable) return true;
9465
9466 // TODO: introduce a tri-valued comparison for overload
9467 // candidates. Would be more worthwhile if we had a sort
9468 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00009469 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9470 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00009471 } else if (R->Viable)
9472 return false;
John McCall12f97bc2010-01-08 04:41:39 +00009473
John McCall3712d9e2010-01-15 23:32:50 +00009474 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00009475
John McCall3712d9e2010-01-15 23:32:50 +00009476 // Criteria by which we can sort non-viable candidates:
9477 if (!L->Viable) {
9478 // 1. Arity mismatches come after other candidates.
9479 if (L->FailureKind == ovl_fail_too_many_arguments ||
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009480 L->FailureKind == ovl_fail_too_few_arguments) {
9481 if (R->FailureKind == ovl_fail_too_many_arguments ||
9482 R->FailureKind == ovl_fail_too_few_arguments) {
Kaelyn Takata50c4ffc2014-05-07 00:43:38 +00009483 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9484 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9485 if (LDist == RDist) {
9486 if (L->FailureKind == R->FailureKind)
9487 // Sort non-surrogates before surrogates.
9488 return !L->IsSurrogate && R->IsSurrogate;
9489 // Sort candidates requiring fewer parameters than there were
9490 // arguments given after candidates requiring more parameters
9491 // than there were arguments given.
9492 return L->FailureKind == ovl_fail_too_many_arguments;
9493 }
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009494 return LDist < RDist;
9495 }
John McCall3712d9e2010-01-15 23:32:50 +00009496 return false;
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009497 }
John McCall3712d9e2010-01-15 23:32:50 +00009498 if (R->FailureKind == ovl_fail_too_many_arguments ||
9499 R->FailureKind == ovl_fail_too_few_arguments)
9500 return true;
John McCall12f97bc2010-01-08 04:41:39 +00009501
John McCallfe796dd2010-01-23 05:17:32 +00009502 // 2. Bad conversions come first and are ordered by the number
9503 // of bad conversions and quality of good conversions.
9504 if (L->FailureKind == ovl_fail_bad_conversion) {
9505 if (R->FailureKind != ovl_fail_bad_conversion)
9506 return true;
9507
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009508 // The conversion that can be fixed with a smaller number of changes,
9509 // comes first.
9510 unsigned numLFixes = L->Fix.NumConversionsFixed;
9511 unsigned numRFixes = R->Fix.NumConversionsFixed;
9512 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9513 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009514 if (numLFixes != numRFixes) {
David Blaikie7a3cbb22015-03-09 02:02:07 +00009515 return numLFixes < numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009516 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009517
John McCallfe796dd2010-01-23 05:17:32 +00009518 // If there's any ordering between the defined conversions...
9519 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00009520 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00009521
9522 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00009523 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009524 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00009525 switch (CompareImplicitConversionSequences(S,
9526 L->Conversions[I],
9527 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00009528 case ImplicitConversionSequence::Better:
9529 leftBetter++;
9530 break;
9531
9532 case ImplicitConversionSequence::Worse:
9533 leftBetter--;
9534 break;
9535
9536 case ImplicitConversionSequence::Indistinguishable:
9537 break;
9538 }
9539 }
9540 if (leftBetter > 0) return true;
9541 if (leftBetter < 0) return false;
9542
9543 } else if (R->FailureKind == ovl_fail_bad_conversion)
9544 return false;
9545
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009546 if (L->FailureKind == ovl_fail_bad_deduction) {
9547 if (R->FailureKind != ovl_fail_bad_deduction)
9548 return true;
9549
9550 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9551 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00009552 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00009553 } else if (R->FailureKind == ovl_fail_bad_deduction)
9554 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009555
John McCall3712d9e2010-01-15 23:32:50 +00009556 // TODO: others?
9557 }
9558
9559 // Sort everything else by location.
9560 SourceLocation LLoc = GetLocationForCandidate(L);
9561 SourceLocation RLoc = GetLocationForCandidate(R);
9562
9563 // Put candidates without locations (e.g. builtins) at the end.
9564 if (LLoc.isInvalid()) return false;
9565 if (RLoc.isInvalid()) return true;
9566
9567 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00009568 }
9569};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009570}
John McCall12f97bc2010-01-08 04:41:39 +00009571
John McCallfe796dd2010-01-23 05:17:32 +00009572/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009573/// computes up to the first. Produces the FixIt set if possible.
Richard Smith17c00b42014-11-12 01:24:00 +00009574static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9575 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00009576 assert(!Cand->Viable);
9577
9578 // Don't do anything on failures other than bad conversion.
9579 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9580
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009581 // We only want the FixIts if all the arguments can be corrected.
9582 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00009583 // Use a implicit copy initialization to check conversion fixes.
9584 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009585
John McCallfe796dd2010-01-23 05:17:32 +00009586 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00009587 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009588 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00009589 while (true) {
9590 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9591 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009592 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00009593 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00009594 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009595 }
John McCallfe796dd2010-01-23 05:17:32 +00009596 }
9597
9598 if (ConvIdx == ConvCount)
9599 return;
9600
John McCall65eb8792010-02-25 01:37:24 +00009601 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9602 "remaining conversion is initialized?");
9603
Douglas Gregoradc7a702010-04-16 17:45:54 +00009604 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00009605 // operation somehow.
9606 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00009607
9608 const FunctionProtoType* Proto;
9609 unsigned ArgIdx = ConvIdx;
9610
9611 if (Cand->IsSurrogate) {
9612 QualType ConvType
9613 = Cand->Surrogate->getConversionType().getNonReferenceType();
9614 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9615 ConvType = ConvPtrType->getPointeeType();
9616 Proto = ConvType->getAs<FunctionProtoType>();
9617 ArgIdx--;
9618 } else if (Cand->Function) {
9619 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9620 if (isa<CXXMethodDecl>(Cand->Function) &&
9621 !isa<CXXConstructorDecl>(Cand->Function))
9622 ArgIdx--;
9623 } else {
9624 // Builtin binary operator with a bad first conversion.
9625 assert(ConvCount <= 3);
9626 for (; ConvIdx != ConvCount; ++ConvIdx)
9627 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00009628 = TryCopyInitialization(S, Args[ConvIdx],
9629 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009630 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00009631 /*InOverloadResolution*/ true,
9632 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00009633 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00009634 return;
9635 }
9636
9637 // Fill in the rest of the conversions.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009638 unsigned NumParams = Proto->getNumParams();
John McCallfe796dd2010-01-23 05:17:32 +00009639 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009640 if (ArgIdx < NumParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009641 Cand->Conversions[ConvIdx] = TryCopyInitialization(
9642 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
9643 /*InOverloadResolution=*/true,
9644 /*AllowObjCWritebackConversion=*/
9645 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009646 // Store the FixIt in the candidate if it exists.
9647 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00009648 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009649 }
John McCallfe796dd2010-01-23 05:17:32 +00009650 else
9651 Cand->Conversions[ConvIdx].setEllipsis();
9652 }
9653}
9654
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009655/// PrintOverloadCandidates - When overload resolution fails, prints
9656/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00009657/// set.
John McCall5c32be02010-08-24 20:38:10 +00009658void OverloadCandidateSet::NoteCandidates(Sema &S,
9659 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009660 ArrayRef<Expr *> Args,
David Blaikie1d202a62012-10-08 01:11:04 +00009661 StringRef Opc,
John McCall5c32be02010-08-24 20:38:10 +00009662 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00009663 // Sort the candidates by viability and position. Sorting directly would
9664 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009665 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00009666 if (OCD == OCD_AllCandidates) Cands.reserve(size());
9667 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00009668 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00009669 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00009670 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009671 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009672 if (Cand->Function || Cand->IsSurrogate)
9673 Cands.push_back(Cand);
9674 // Otherwise, this a non-viable builtin candidate. We do not, in general,
9675 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00009676 }
9677 }
9678
John McCallad2587a2010-01-12 00:48:53 +00009679 std::sort(Cands.begin(), Cands.end(),
Kaelyn Takatab96b3be2014-05-01 21:15:24 +00009680 CompareOverloadCandidatesForDisplay(S, Args.size()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009681
John McCall0d1da222010-01-12 00:44:57 +00009682 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00009683
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009684 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +00009685 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009686 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00009687 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9688 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00009689
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009690 // Set an arbitrary limit on the number of candidate functions we'll spam
9691 // the user with. FIXME: This limit should depend on details of the
9692 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +00009693 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009694 break;
9695 }
9696 ++CandsShown;
9697
John McCalld3224162010-01-08 00:58:21 +00009698 if (Cand->Function)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009699 NoteFunctionCandidate(S, Cand, Args.size());
John McCalld3224162010-01-08 00:58:21 +00009700 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00009701 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009702 else {
9703 assert(Cand->Viable &&
9704 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00009705 // Generally we only see ambiguities including viable builtin
9706 // operators if overload resolution got screwed up by an
9707 // ambiguous user-defined conversion.
9708 //
9709 // FIXME: It's quite possible for different conversions to see
9710 // different ambiguities, though.
9711 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00009712 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00009713 ReportedAmbiguousConversions = true;
9714 }
John McCalld3224162010-01-08 00:58:21 +00009715
John McCall0d1da222010-01-12 00:44:57 +00009716 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00009717 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00009718 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009719 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009720
9721 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00009722 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009723}
9724
Larisse Voufo98b20f12013-07-19 23:00:19 +00009725static SourceLocation
9726GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9727 return Cand->Specialization ? Cand->Specialization->getLocation()
9728 : SourceLocation();
9729}
9730
Richard Smith17c00b42014-11-12 01:24:00 +00009731namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009732struct CompareTemplateSpecCandidatesForDisplay {
9733 Sema &S;
9734 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9735
9736 bool operator()(const TemplateSpecCandidate *L,
9737 const TemplateSpecCandidate *R) {
9738 // Fast-path this check.
9739 if (L == R)
9740 return false;
9741
9742 // Assuming that both candidates are not matches...
9743
9744 // Sort by the ranking of deduction failures.
9745 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9746 return RankDeductionFailure(L->DeductionFailure) <
9747 RankDeductionFailure(R->DeductionFailure);
9748
9749 // Sort everything else by location.
9750 SourceLocation LLoc = GetLocationForCandidate(L);
9751 SourceLocation RLoc = GetLocationForCandidate(R);
9752
9753 // Put candidates without locations (e.g. builtins) at the end.
9754 if (LLoc.isInvalid())
9755 return false;
9756 if (RLoc.isInvalid())
9757 return true;
9758
9759 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9760 }
9761};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009762}
Larisse Voufo98b20f12013-07-19 23:00:19 +00009763
9764/// Diagnose a template argument deduction failure.
9765/// We are treating these failures as overload failures due to bad
9766/// deductions.
9767void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9768 DiagnoseBadDeduction(S, Specialization, // pattern
9769 DeductionFailure, /*NumArgs=*/0);
9770}
9771
9772void TemplateSpecCandidateSet::destroyCandidates() {
9773 for (iterator i = begin(), e = end(); i != e; ++i) {
9774 i->DeductionFailure.Destroy();
9775 }
9776}
9777
9778void TemplateSpecCandidateSet::clear() {
9779 destroyCandidates();
9780 Candidates.clear();
9781}
9782
9783/// NoteCandidates - When no template specialization match is found, prints
9784/// diagnostic messages containing the non-matching specializations that form
9785/// the candidate set.
9786/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9787/// OCD == OCD_AllCandidates and Cand->Viable == false.
9788void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9789 // Sort the candidates by position (assuming no candidate is a match).
9790 // Sorting directly would be prohibitive, so we make a set of pointers
9791 // and sort those.
9792 SmallVector<TemplateSpecCandidate *, 32> Cands;
9793 Cands.reserve(size());
9794 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9795 if (Cand->Specialization)
9796 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +00009797 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +00009798 // in general, want to list every possible builtin candidate.
9799 }
9800
9801 std::sort(Cands.begin(), Cands.end(),
9802 CompareTemplateSpecCandidatesForDisplay(S));
9803
9804 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9805 // for generalization purposes (?).
9806 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9807
9808 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9809 unsigned CandsShown = 0;
9810 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9811 TemplateSpecCandidate *Cand = *I;
9812
9813 // Set an arbitrary limit on the number of candidates we'll spam
9814 // the user with. FIXME: This limit should depend on details of the
9815 // candidate list.
9816 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9817 break;
9818 ++CandsShown;
9819
9820 assert(Cand->Specialization &&
9821 "Non-matching built-in candidates are not added to Cands.");
9822 Cand->NoteDeductionFailure(S);
9823 }
9824
9825 if (I != E)
9826 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9827}
9828
Douglas Gregorb491ed32011-02-19 21:32:49 +00009829// [PossiblyAFunctionType] --> [Return]
9830// NonFunctionType --> NonFunctionType
9831// R (A) --> R(A)
9832// R (*)(A) --> R (A)
9833// R (&)(A) --> R (A)
9834// R (S::*)(A) --> R (A)
9835QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9836 QualType Ret = PossiblyAFunctionType;
9837 if (const PointerType *ToTypePtr =
9838 PossiblyAFunctionType->getAs<PointerType>())
9839 Ret = ToTypePtr->getPointeeType();
9840 else if (const ReferenceType *ToTypeRef =
9841 PossiblyAFunctionType->getAs<ReferenceType>())
9842 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009843 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00009844 PossiblyAFunctionType->getAs<MemberPointerType>())
9845 Ret = MemTypePtr->getPointeeType();
9846 Ret =
9847 Context.getCanonicalType(Ret).getUnqualifiedType();
9848 return Ret;
9849}
Douglas Gregorcd695e52008-11-10 20:40:00 +00009850
Richard Smith17c00b42014-11-12 01:24:00 +00009851namespace {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009852// A helper class to help with address of function resolution
9853// - allows us to avoid passing around all those ugly parameters
Richard Smith17c00b42014-11-12 01:24:00 +00009854class AddressOfFunctionResolver {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009855 Sema& S;
9856 Expr* SourceExpr;
9857 const QualType& TargetType;
9858 QualType TargetFunctionType; // Extracted function type from target type
9859
9860 bool Complain;
9861 //DeclAccessPair& ResultFunctionAccessPair;
9862 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009863
Douglas Gregorb491ed32011-02-19 21:32:49 +00009864 bool TargetTypeIsNonStaticMemberFunction;
9865 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +00009866 bool StaticMemberFunctionFromBoundPointer;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009867
Douglas Gregorb491ed32011-02-19 21:32:49 +00009868 OverloadExpr::FindResult OvlExprInfo;
9869 OverloadExpr *OvlExpr;
9870 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009871 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009872 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009873
Douglas Gregorb491ed32011-02-19 21:32:49 +00009874public:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009875 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9876 const QualType &TargetType, bool Complain)
9877 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9878 Complain(Complain), Context(S.getASTContext()),
9879 TargetTypeIsNonStaticMemberFunction(
9880 !!TargetType->getAs<MemberPointerType>()),
9881 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +00009882 StaticMemberFunctionFromBoundPointer(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +00009883 OvlExprInfo(OverloadExpr::find(SourceExpr)),
9884 OvlExpr(OvlExprInfo.Expression),
9885 FailedCandidates(OvlExpr->getNameLoc()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009886 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +00009887
David Majnemera4f7c7a2013-08-01 06:13:59 +00009888 if (TargetFunctionType->isFunctionType()) {
9889 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9890 if (!UME->isImplicitAccess() &&
9891 !S.ResolveSingleFunctionTemplateSpecialization(UME))
9892 StaticMemberFunctionFromBoundPointer = true;
9893 } else if (OvlExpr->hasExplicitTemplateArgs()) {
9894 DeclAccessPair dap;
9895 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9896 OvlExpr, false, &dap)) {
9897 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9898 if (!Method->isStatic()) {
9899 // If the target type is a non-function type and the function found
9900 // is a non-static member function, pretend as if that was the
9901 // target, it's the only possible type to end up with.
9902 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +00009903
David Majnemera4f7c7a2013-08-01 06:13:59 +00009904 // And skip adding the function if its not in the proper form.
9905 // We'll diagnose this due to an empty set of functions.
9906 if (!OvlExprInfo.HasFormOfMemberPointer)
9907 return;
Chandler Carruthffce2452011-03-29 08:08:18 +00009908 }
9909
David Majnemera4f7c7a2013-08-01 06:13:59 +00009910 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +00009911 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009912 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00009913 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009914
9915 if (OvlExpr->hasExplicitTemplateArgs())
9916 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00009917
Douglas Gregorb491ed32011-02-19 21:32:49 +00009918 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9919 // C++ [over.over]p4:
9920 // If more than one function is selected, [...]
9921 if (Matches.size() > 1) {
9922 if (FoundNonTemplateFunction)
9923 EliminateAllTemplateMatches();
9924 else
9925 EliminateAllExceptMostSpecializedTemplate();
9926 }
9927 }
9928 }
9929
9930private:
9931 bool isTargetTypeAFunction() const {
9932 return TargetFunctionType->isFunctionType();
9933 }
9934
9935 // [ToType] [Return]
9936
9937 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9938 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9939 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9940 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9941 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9942 }
9943
9944 // return true if any matching specializations were found
9945 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9946 const DeclAccessPair& CurAccessFunPair) {
9947 if (CXXMethodDecl *Method
9948 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9949 // Skip non-static function templates when converting to pointer, and
9950 // static when converting to member pointer.
9951 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9952 return false;
9953 }
9954 else if (TargetTypeIsNonStaticMemberFunction)
9955 return false;
9956
9957 // C++ [over.over]p2:
9958 // If the name is a function template, template argument deduction is
9959 // done (14.8.2.2), and if the argument deduction succeeds, the
9960 // resulting template argument list is used to generate a single
9961 // function template specialization, which is added to the set of
9962 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +00009963 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009964 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +00009965 if (Sema::TemplateDeductionResult Result
9966 = S.DeduceTemplateArguments(FunctionTemplate,
9967 &OvlExplicitTemplateArgs,
9968 TargetFunctionType, Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00009969 Info, /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009970 // Make a note of the failed deduction for diagnostics.
9971 FailedCandidates.addCandidate()
9972 .set(FunctionTemplate->getTemplatedDecl(),
9973 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +00009974 return false;
9975 }
9976
Douglas Gregor19a41f12013-04-17 08:45:07 +00009977 // Template argument deduction ensures that we have an exact match or
9978 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009979 // This function template specicalization works.
9980 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Douglas Gregor19a41f12013-04-17 08:45:07 +00009981 assert(S.isSameOrCompatibleFunctionType(
9982 Context.getCanonicalType(Specialization->getType()),
9983 Context.getCanonicalType(TargetFunctionType)));
Douglas Gregorb491ed32011-02-19 21:32:49 +00009984 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9985 return true;
9986 }
9987
9988 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9989 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009990 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009991 // Skip non-static functions when converting to pointer, and static
9992 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009993 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9994 return false;
9995 }
9996 else if (TargetTypeIsNonStaticMemberFunction)
9997 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009998
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009999 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010000 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010001 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
Eli Bendersky9a220fc2014-09-29 20:38:29 +000010002 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl))
Peter Collingbourne7277fe82011-10-02 23:49:40 +000010003 return false;
10004
Richard Smith2a7d4812013-05-04 07:00:32 +000010005 // If any candidate has a placeholder return type, trigger its deduction
10006 // now.
Aaron Ballmandd69ef32014-08-19 15:55:55 +000010007 if (S.getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +000010008 FunDecl->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +000010009 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
10010 return false;
10011
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000010012 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010013 if (Context.hasSameUnqualifiedType(TargetFunctionType,
10014 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +000010015 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
10016 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010017 Matches.push_back(std::make_pair(CurAccessFunPair,
10018 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010019 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010020 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +000010021 }
Mike Stump11289f42009-09-09 15:08:12 +000010022 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010023
10024 return false;
10025 }
10026
10027 bool FindAllFunctionsThatMatchTargetTypeExactly() {
10028 bool Ret = false;
10029
10030 // If the overload expression doesn't have the form of a pointer to
10031 // member, don't try to convert it to a pointer-to-member type.
10032 if (IsInvalidFormOfPointerToMemberFunction())
10033 return false;
10034
10035 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10036 E = OvlExpr->decls_end();
10037 I != E; ++I) {
10038 // Look through any using declarations to find the underlying function.
10039 NamedDecl *Fn = (*I)->getUnderlyingDecl();
10040
10041 // C++ [over.over]p3:
10042 // Non-member functions and static member functions match
10043 // targets of type "pointer-to-function" or "reference-to-function."
10044 // Nonstatic member functions match targets of
10045 // type "pointer-to-member-function."
10046 // Note that according to DR 247, the containing class does not matter.
10047 if (FunctionTemplateDecl *FunctionTemplate
10048 = dyn_cast<FunctionTemplateDecl>(Fn)) {
10049 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
10050 Ret = true;
10051 }
10052 // If we have explicit template arguments supplied, skip non-templates.
10053 else if (!OvlExpr->hasExplicitTemplateArgs() &&
10054 AddMatchingNonTemplateFunction(Fn, I.getPair()))
10055 Ret = true;
10056 }
10057 assert(Ret || Matches.empty());
10058 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010059 }
10060
Douglas Gregorb491ed32011-02-19 21:32:49 +000010061 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +000010062 // [...] and any given function template specialization F1 is
10063 // eliminated if the set contains a second function template
10064 // specialization whose function template is more specialized
10065 // than the function template of F1 according to the partial
10066 // ordering rules of 14.5.5.2.
10067
10068 // The algorithm specified above is quadratic. We instead use a
10069 // two-pass algorithm (similar to the one used to identify the
10070 // best viable function in an overload set) that identifies the
10071 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +000010072
10073 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
10074 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
10075 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010076
Larisse Voufo98b20f12013-07-19 23:00:19 +000010077 // TODO: It looks like FailedCandidates does not serve much purpose
10078 // here, since the no_viable diagnostic has index 0.
10079 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +000010080 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +000010081 SourceExpr->getLocStart(), S.PDiag(),
10082 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
10083 .second->getDeclName(),
10084 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
10085 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010086
Douglas Gregorb491ed32011-02-19 21:32:49 +000010087 if (Result != MatchesCopy.end()) {
10088 // Make it the first and only element
10089 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
10090 Matches[0].second = cast<FunctionDecl>(*Result);
10091 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +000010092 }
10093 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010094
Douglas Gregorb491ed32011-02-19 21:32:49 +000010095 void EliminateAllTemplateMatches() {
10096 // [...] any function template specializations in the set are
10097 // eliminated if the set also contains a non-template function, [...]
10098 for (unsigned I = 0, N = Matches.size(); I != N; ) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010099 if (Matches[I].second->getPrimaryTemplate() == nullptr)
Douglas Gregorb491ed32011-02-19 21:32:49 +000010100 ++I;
10101 else {
10102 Matches[I] = Matches[--N];
10103 Matches.set_size(N);
10104 }
10105 }
10106 }
10107
10108public:
10109 void ComplainNoMatchesFound() const {
10110 assert(Matches.empty());
10111 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
10112 << OvlExpr->getName() << TargetFunctionType
10113 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +000010114 if (FailedCandidates.empty())
10115 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
10116 else {
10117 // We have some deduction failure messages. Use them to diagnose
10118 // the function templates, and diagnose the non-template candidates
10119 // normally.
10120 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10121 IEnd = OvlExpr->decls_end();
10122 I != IEnd; ++I)
10123 if (FunctionDecl *Fun =
10124 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
10125 S.NoteOverloadCandidate(Fun, TargetFunctionType);
10126 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
10127 }
10128 }
10129
Douglas Gregorb491ed32011-02-19 21:32:49 +000010130 bool IsInvalidFormOfPointerToMemberFunction() const {
10131 return TargetTypeIsNonStaticMemberFunction &&
10132 !OvlExprInfo.HasFormOfMemberPointer;
10133 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010134
Douglas Gregorb491ed32011-02-19 21:32:49 +000010135 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
10136 // TODO: Should we condition this on whether any functions might
10137 // have matched, or is it more appropriate to do that in callers?
10138 // TODO: a fixit wouldn't hurt.
10139 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
10140 << TargetType << OvlExpr->getSourceRange();
10141 }
David Majnemera4f7c7a2013-08-01 06:13:59 +000010142
10143 bool IsStaticMemberFunctionFromBoundPointer() const {
10144 return StaticMemberFunctionFromBoundPointer;
10145 }
10146
10147 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
10148 S.Diag(OvlExpr->getLocStart(),
10149 diag::err_invalid_form_pointer_member_function)
10150 << OvlExpr->getSourceRange();
10151 }
10152
Douglas Gregorb491ed32011-02-19 21:32:49 +000010153 void ComplainOfInvalidConversion() const {
10154 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
10155 << OvlExpr->getName() << TargetType;
10156 }
10157
10158 void ComplainMultipleMatchesFound() const {
10159 assert(Matches.size() > 1);
10160 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
10161 << OvlExpr->getName()
10162 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +000010163 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010164 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010165
10166 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
10167
Douglas Gregorb491ed32011-02-19 21:32:49 +000010168 int getNumMatches() const { return Matches.size(); }
10169
10170 FunctionDecl* getMatchingFunctionDecl() 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].second;
10173 }
10174
10175 const DeclAccessPair* getMatchingFunctionAccessPair() const {
Craig Topperc3ec1492014-05-26 06:22:03 +000010176 if (Matches.size() != 1) return nullptr;
Douglas Gregorb491ed32011-02-19 21:32:49 +000010177 return &Matches[0].first;
10178 }
10179};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010180}
Richard Smith17c00b42014-11-12 01:24:00 +000010181
Douglas Gregorb491ed32011-02-19 21:32:49 +000010182/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
10183/// an overloaded function (C++ [over.over]), where @p From is an
10184/// expression with overloaded function type and @p ToType is the type
10185/// we're trying to resolve to. For example:
10186///
10187/// @code
10188/// int f(double);
10189/// int f(int);
10190///
10191/// int (*pfd)(double) = f; // selects f(double)
10192/// @endcode
10193///
10194/// This routine returns the resulting FunctionDecl if it could be
10195/// resolved, and NULL otherwise. When @p Complain is true, this
10196/// routine will emit diagnostics if there is an error.
10197FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010198Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
10199 QualType TargetType,
10200 bool Complain,
10201 DeclAccessPair &FoundResult,
10202 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010203 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010204
10205 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
10206 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010207 int NumMatches = Resolver.getNumMatches();
Craig Topperc3ec1492014-05-26 06:22:03 +000010208 FunctionDecl *Fn = nullptr;
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010209 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010210 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
10211 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
10212 else
10213 Resolver.ComplainNoMatchesFound();
10214 }
10215 else if (NumMatches > 1 && Complain)
10216 Resolver.ComplainMultipleMatchesFound();
10217 else if (NumMatches == 1) {
10218 Fn = Resolver.getMatchingFunctionDecl();
10219 assert(Fn);
10220 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +000010221 if (Complain) {
10222 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10223 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10224 else
10225 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10226 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +000010227 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +000010228
10229 if (pHadMultipleCandidates)
10230 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +000010231 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010232}
10233
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010234/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010235/// resolve that overloaded function expression down to a single function.
10236///
10237/// This routine can only resolve template-ids that refer to a single function
10238/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010239/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010240/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +000010241///
10242/// If no template-ids are found, no diagnostics are emitted and NULL is
10243/// returned.
John McCall0009fcc2011-04-26 20:42:42 +000010244FunctionDecl *
10245Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10246 bool Complain,
10247 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010248 // C++ [over.over]p1:
10249 // [...] [Note: any redundant set of parentheses surrounding the
10250 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010251 // C++ [over.over]p1:
10252 // [...] The overloaded function name can be preceded by the &
10253 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010254
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010255 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +000010256 if (!ovl->hasExplicitTemplateArgs())
Craig Topperc3ec1492014-05-26 06:22:03 +000010257 return nullptr;
John McCall1acbbb52010-02-02 06:20:04 +000010258
10259 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +000010260 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +000010261 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010262
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010263 // Look through all of the overloaded functions, searching for one
10264 // whose type matches exactly.
Craig Topperc3ec1492014-05-26 06:22:03 +000010265 FunctionDecl *Matched = nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010266 for (UnresolvedSetIterator I = ovl->decls_begin(),
10267 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010268 // C++0x [temp.arg.explicit]p3:
10269 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010270 // where deduction is not done, if a template argument list is
10271 // specified and it, along with any default template arguments,
10272 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010273 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +000010274 FunctionTemplateDecl *FunctionTemplate
10275 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010276
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010277 // C++ [over.over]p2:
10278 // If the name is a function template, template argument deduction is
10279 // done (14.8.2.2), and if the argument deduction succeeds, the
10280 // resulting template argument list is used to generate a single
10281 // function template specialization, which is added to the set of
10282 // overloaded functions considered.
Craig Topperc3ec1492014-05-26 06:22:03 +000010283 FunctionDecl *Specialization = nullptr;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010284 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010285 if (TemplateDeductionResult Result
10286 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000010287 Specialization, Info,
10288 /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010289 // Make a note of the failed deduction for diagnostics.
10290 // TODO: Actually use the failed-deduction info?
10291 FailedCandidates.addCandidate()
10292 .set(FunctionTemplate->getTemplatedDecl(),
10293 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010294 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010295 }
10296
John McCall0009fcc2011-04-26 20:42:42 +000010297 assert(Specialization && "no specialization and no error?");
10298
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010299 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010300 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010301 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000010302 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10303 << ovl->getName();
10304 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010305 }
Craig Topperc3ec1492014-05-26 06:22:03 +000010306 return nullptr;
John McCall0009fcc2011-04-26 20:42:42 +000010307 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010308
John McCall0009fcc2011-04-26 20:42:42 +000010309 Matched = Specialization;
10310 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010311 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010312
Aaron Ballmandd69ef32014-08-19 15:55:55 +000010313 if (Matched && getLangOpts().CPlusPlus14 &&
Alp Toker314cc812014-01-25 16:55:45 +000010314 Matched->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +000010315 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
Craig Topperc3ec1492014-05-26 06:22:03 +000010316 return nullptr;
Richard Smith2a7d4812013-05-04 07:00:32 +000010317
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010318 return Matched;
10319}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010320
Douglas Gregor1beec452011-03-12 01:48:56 +000010321
10322
10323
John McCall50a2c2c2011-10-11 23:14:30 +000010324// Resolve and fix an overloaded expression that can be resolved
10325// because it identifies a single function template specialization.
10326//
Douglas Gregor1beec452011-03-12 01:48:56 +000010327// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000010328//
10329// Return true if it was logically possible to so resolve the
10330// expression, regardless of whether or not it succeeded. Always
10331// returns true if 'complain' is set.
10332bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10333 ExprResult &SrcExpr, bool doFunctionPointerConverion,
10334 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +000010335 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000010336 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000010337 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000010338
John McCall50a2c2c2011-10-11 23:14:30 +000010339 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000010340
John McCall0009fcc2011-04-26 20:42:42 +000010341 DeclAccessPair found;
10342 ExprResult SingleFunctionExpression;
10343 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10344 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010345 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000010346 SrcExpr = ExprError();
10347 return true;
10348 }
John McCall0009fcc2011-04-26 20:42:42 +000010349
10350 // It is only correct to resolve to an instance method if we're
10351 // resolving a form that's permitted to be a pointer to member.
10352 // Otherwise we'll end up making a bound member expression, which
10353 // is illegal in all the contexts we resolve like this.
10354 if (!ovl.HasFormOfMemberPointer &&
10355 isa<CXXMethodDecl>(fn) &&
10356 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000010357 if (!complain) return false;
10358
10359 Diag(ovl.Expression->getExprLoc(),
10360 diag::err_bound_member_function)
10361 << 0 << ovl.Expression->getSourceRange();
10362
10363 // TODO: I believe we only end up here if there's a mix of
10364 // static and non-static candidates (otherwise the expression
10365 // would have 'bound member' type, not 'overload' type).
10366 // Ideally we would note which candidate was chosen and why
10367 // the static candidates were rejected.
10368 SrcExpr = ExprError();
10369 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010370 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010371
Sylvestre Ledrua5202662012-07-31 06:56:50 +000010372 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000010373 SingleFunctionExpression =
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010374 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
John McCall0009fcc2011-04-26 20:42:42 +000010375
10376 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000010377 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000010378 SingleFunctionExpression =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010379 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
John McCall50a2c2c2011-10-11 23:14:30 +000010380 if (SingleFunctionExpression.isInvalid()) {
10381 SrcExpr = ExprError();
10382 return true;
10383 }
10384 }
John McCall0009fcc2011-04-26 20:42:42 +000010385 }
10386
10387 if (!SingleFunctionExpression.isUsable()) {
10388 if (complain) {
10389 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10390 << ovl.Expression->getName()
10391 << DestTypeForComplaining
10392 << OpRangeForComplaining
10393 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000010394 NoteAllOverloadCandidates(SrcExpr.get());
10395
10396 SrcExpr = ExprError();
10397 return true;
10398 }
10399
10400 return false;
John McCall0009fcc2011-04-26 20:42:42 +000010401 }
10402
John McCall50a2c2c2011-10-11 23:14:30 +000010403 SrcExpr = SingleFunctionExpression;
10404 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010405}
10406
Douglas Gregorcabea402009-09-22 15:41:20 +000010407/// \brief Add a single candidate to the overload set.
10408static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000010409 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000010410 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010411 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010412 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000010413 bool PartialOverloading,
10414 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000010415 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000010416 if (isa<UsingShadowDecl>(Callee))
10417 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10418
Douglas Gregorcabea402009-09-22 15:41:20 +000010419 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000010420 if (ExplicitTemplateArgs) {
10421 assert(!KnownValid && "Explicit template arguments?");
10422 return;
10423 }
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010424 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
10425 /*SuppressUsedConversions=*/false,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010426 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010427 return;
John McCalld14a8642009-11-21 08:51:07 +000010428 }
10429
10430 if (FunctionTemplateDecl *FuncTemplate
10431 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000010432 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010433 ExplicitTemplateArgs, Args, CandidateSet,
10434 /*SuppressUsedConversions=*/false,
10435 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +000010436 return;
10437 }
10438
Richard Smith95ce4f62011-06-26 22:19:54 +000010439 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000010440}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010441
Douglas Gregorcabea402009-09-22 15:41:20 +000010442/// \brief Add the overload candidates named by callee and/or found by argument
10443/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000010444void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010445 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010446 OverloadCandidateSet &CandidateSet,
10447 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000010448
10449#ifndef NDEBUG
10450 // Verify that ArgumentDependentLookup is consistent with the rules
10451 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000010452 //
Douglas Gregorcabea402009-09-22 15:41:20 +000010453 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10454 // and let Y be the lookup set produced by argument dependent
10455 // lookup (defined as follows). If X contains
10456 //
10457 // -- a declaration of a class member, or
10458 //
10459 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000010460 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000010461 //
10462 // -- a declaration that is neither a function or a function
10463 // template
10464 //
10465 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000010466
John McCall57500772009-12-16 12:17:52 +000010467 if (ULE->requiresADL()) {
10468 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10469 E = ULE->decls_end(); I != E; ++I) {
10470 assert(!(*I)->getDeclContext()->isRecord());
10471 assert(isa<UsingShadowDecl>(*I) ||
10472 !(*I)->getDeclContext()->isFunctionOrMethod());
10473 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000010474 }
10475 }
10476#endif
10477
John McCall57500772009-12-16 12:17:52 +000010478 // It would be nice to avoid this copy.
10479 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000010480 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000010481 if (ULE->hasExplicitTemplateArgs()) {
10482 ULE->copyTemplateArgumentsInto(TABuffer);
10483 ExplicitTemplateArgs = &TABuffer;
10484 }
10485
10486 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10487 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010488 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10489 CandidateSet, PartialOverloading,
10490 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000010491
John McCall57500772009-12-16 12:17:52 +000010492 if (ULE->requiresADL())
Richard Smith100b24a2014-04-17 01:52:14 +000010493 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010494 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000010495 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010496}
John McCalld681c392009-12-16 08:11:27 +000010497
Richard Smith0603bbb2013-06-12 22:56:54 +000010498/// Determine whether a declaration with the specified name could be moved into
10499/// a different namespace.
10500static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10501 switch (Name.getCXXOverloadedOperator()) {
10502 case OO_New: case OO_Array_New:
10503 case OO_Delete: case OO_Array_Delete:
10504 return false;
10505
10506 default:
10507 return true;
10508 }
10509}
10510
Richard Smith998a5912011-06-05 22:42:48 +000010511/// Attempt to recover from an ill-formed use of a non-dependent name in a
10512/// template, where the non-dependent name was declared after the template
10513/// was defined. This is common in code written for a compilers which do not
10514/// correctly implement two-stage name lookup.
10515///
10516/// Returns true if a viable candidate was found and a diagnostic was issued.
10517static bool
10518DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10519 const CXXScopeSpec &SS, LookupResult &R,
Richard Smith100b24a2014-04-17 01:52:14 +000010520 OverloadCandidateSet::CandidateSetKind CSK,
Richard Smith998a5912011-06-05 22:42:48 +000010521 TemplateArgumentListInfo *ExplicitTemplateArgs,
Hans Wennborg64937c62015-06-11 21:21:57 +000010522 ArrayRef<Expr *> Args,
10523 bool *DoDiagnoseEmptyLookup = nullptr) {
Richard Smith998a5912011-06-05 22:42:48 +000010524 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10525 return false;
10526
10527 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000010528 if (DC->isTransparentContext())
10529 continue;
10530
Richard Smith998a5912011-06-05 22:42:48 +000010531 SemaRef.LookupQualifiedName(R, DC);
10532
10533 if (!R.empty()) {
10534 R.suppressDiagnostics();
10535
10536 if (isa<CXXRecordDecl>(DC)) {
10537 // Don't diagnose names we find in classes; we get much better
10538 // diagnostics for these from DiagnoseEmptyLookup.
10539 R.clear();
Hans Wennborg64937c62015-06-11 21:21:57 +000010540 if (DoDiagnoseEmptyLookup)
10541 *DoDiagnoseEmptyLookup = true;
Richard Smith998a5912011-06-05 22:42:48 +000010542 return false;
10543 }
10544
Richard Smith100b24a2014-04-17 01:52:14 +000010545 OverloadCandidateSet Candidates(FnLoc, CSK);
Richard Smith998a5912011-06-05 22:42:48 +000010546 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10547 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010548 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000010549 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000010550
10551 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000010552 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000010553 // No viable functions. Don't bother the user with notes for functions
10554 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000010555 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000010556 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000010557 }
Richard Smith998a5912011-06-05 22:42:48 +000010558
10559 // Find the namespaces where ADL would have looked, and suggest
10560 // declaring the function there instead.
10561 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10562 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000010563 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000010564 AssociatedNamespaces,
10565 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000010566 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000010567 if (canBeDeclaredInNamespace(R.getLookupName())) {
10568 DeclContext *Std = SemaRef.getStdNamespace();
10569 for (Sema::AssociatedNamespaceSet::iterator
10570 it = AssociatedNamespaces.begin(),
10571 end = AssociatedNamespaces.end(); it != end; ++it) {
10572 // Never suggest declaring a function within namespace 'std'.
10573 if (Std && Std->Encloses(*it))
10574 continue;
Richard Smith21bae432012-12-22 02:46:14 +000010575
Richard Smith0603bbb2013-06-12 22:56:54 +000010576 // Never suggest declaring a function within a namespace with a
10577 // reserved name, like __gnu_cxx.
10578 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10579 if (NS &&
10580 NS->getQualifiedNameAsString().find("__") != std::string::npos)
10581 continue;
10582
10583 SuggestedNamespaces.insert(*it);
10584 }
Richard Smith998a5912011-06-05 22:42:48 +000010585 }
10586
10587 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10588 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000010589 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000010590 SemaRef.Diag(Best->Function->getLocation(),
10591 diag::note_not_found_by_two_phase_lookup)
10592 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000010593 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000010594 SemaRef.Diag(Best->Function->getLocation(),
10595 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000010596 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000010597 } else {
10598 // FIXME: It would be useful to list the associated namespaces here,
10599 // but the diagnostics infrastructure doesn't provide a way to produce
10600 // a localized representation of a list of items.
10601 SemaRef.Diag(Best->Function->getLocation(),
10602 diag::note_not_found_by_two_phase_lookup)
10603 << R.getLookupName() << 2;
10604 }
10605
10606 // Try to recover by calling this function.
10607 return true;
10608 }
10609
10610 R.clear();
10611 }
10612
10613 return false;
10614}
10615
10616/// Attempt to recover from ill-formed use of a non-dependent operator in a
10617/// template, where the non-dependent operator was declared after the template
10618/// was defined.
10619///
10620/// Returns true if a viable candidate was found and a diagnostic was issued.
10621static bool
10622DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10623 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010624 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000010625 DeclarationName OpName =
10626 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10627 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10628 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Richard Smith100b24a2014-04-17 01:52:14 +000010629 OverloadCandidateSet::CSK_Operator,
Craig Topperc3ec1492014-05-26 06:22:03 +000010630 /*ExplicitTemplateArgs=*/nullptr, Args);
Richard Smith998a5912011-06-05 22:42:48 +000010631}
10632
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010633namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000010634class BuildRecoveryCallExprRAII {
10635 Sema &SemaRef;
10636public:
10637 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10638 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10639 SemaRef.IsBuildingRecoveryCallExpr = true;
10640 }
10641
10642 ~BuildRecoveryCallExprRAII() {
10643 SemaRef.IsBuildingRecoveryCallExpr = false;
10644 }
10645};
10646
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010647}
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010648
Kaelyn Takata89c881b2014-10-27 18:07:29 +000010649static std::unique_ptr<CorrectionCandidateCallback>
10650MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs,
10651 bool HasTemplateArgs, bool AllowTypoCorrection) {
10652 if (!AllowTypoCorrection)
10653 return llvm::make_unique<NoTypoCorrectionCCC>();
10654 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs,
10655 HasTemplateArgs, ME);
10656}
10657
John McCalld681c392009-12-16 08:11:27 +000010658/// Attempts to recover from a call where no functions were found.
10659///
10660/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000010661static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000010662BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000010663 UnresolvedLookupExpr *ULE,
10664 SourceLocation LParenLoc,
Craig Toppere3d2ecbe2014-06-28 23:22:33 +000010665 MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000010666 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010667 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000010668 // Do not try to recover if it is already building a recovery call.
10669 // This stops infinite loops for template instantiations like
10670 //
10671 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10672 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10673 //
10674 if (SemaRef.IsBuildingRecoveryCallExpr)
10675 return ExprError();
10676 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000010677
10678 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000010679 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000010680 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000010681
John McCall57500772009-12-16 12:17:52 +000010682 TemplateArgumentListInfo TABuffer;
Craig Topperc3ec1492014-05-26 06:22:03 +000010683 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
John McCall57500772009-12-16 12:17:52 +000010684 if (ULE->hasExplicitTemplateArgs()) {
10685 ULE->copyTemplateArgumentsInto(TABuffer);
10686 ExplicitTemplateArgs = &TABuffer;
10687 }
10688
John McCalld681c392009-12-16 08:11:27 +000010689 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10690 Sema::LookupOrdinaryName);
Hans Wennborg64937c62015-06-11 21:21:57 +000010691 bool DoDiagnoseEmptyLookup = EmptyLookup;
Richard Smith998a5912011-06-05 22:42:48 +000010692 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Richard Smith100b24a2014-04-17 01:52:14 +000010693 OverloadCandidateSet::CSK_Normal,
Hans Wennborg64937c62015-06-11 21:21:57 +000010694 ExplicitTemplateArgs, Args,
10695 &DoDiagnoseEmptyLookup) &&
10696 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup(
10697 S, SS, R,
10698 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(),
10699 ExplicitTemplateArgs != nullptr, AllowTypoCorrection),
10700 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000010701 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000010702
John McCall57500772009-12-16 12:17:52 +000010703 assert(!R.empty() && "lookup results empty despite recovery");
10704
10705 // Build an implicit member call if appropriate. Just drop the
10706 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000010707 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000010708 if ((*R.begin())->isCXXClassMember())
Aaron Ballman6924dcd2015-09-01 14:49:24 +000010709 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
10710 ExplicitTemplateArgs, S);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000010711 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000010712 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000010713 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000010714 else
10715 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10716
10717 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000010718 return ExprError();
John McCall57500772009-12-16 12:17:52 +000010719
10720 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000010721 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000010722 // end up here.
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010723 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010724 MultiExprArg(Args.data(), Args.size()),
10725 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000010726}
Douglas Gregor4038cf42010-06-08 17:35:15 +000010727
Sam Panzer0f384432012-08-21 00:52:01 +000010728/// \brief Constructs and populates an OverloadedCandidateSet from
10729/// the given function.
10730/// \returns true when an the ExprResult output parameter has been set.
10731bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10732 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010733 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010734 SourceLocation RParenLoc,
10735 OverloadCandidateSet *CandidateSet,
10736 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000010737#ifndef NDEBUG
10738 if (ULE->requiresADL()) {
10739 // To do ADL, we must have found an unqualified name.
10740 assert(!ULE->getQualifier() && "qualified name with ADL");
10741
10742 // We don't perform ADL for implicit declarations of builtins.
10743 // Verify that this was correctly set up.
10744 FunctionDecl *F;
10745 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10746 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10747 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000010748 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010749
John McCall57500772009-12-16 12:17:52 +000010750 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010751 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000010752 }
John McCall57500772009-12-16 12:17:52 +000010753#endif
10754
John McCall4124c492011-10-17 18:40:02 +000010755 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010756 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000010757 *Result = ExprError();
10758 return true;
10759 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000010760
John McCall57500772009-12-16 12:17:52 +000010761 // Add the functions denoted by the callee to the set of candidate
10762 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010763 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000010764
Hans Wennborgb2747382015-06-12 21:23:23 +000010765 if (getLangOpts().MSVCCompat &&
10766 CurContext->isDependentContext() && !isSFINAEContext() &&
Hans Wennborg64937c62015-06-11 21:21:57 +000010767 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
10768
10769 OverloadCandidateSet::iterator Best;
10770 if (CandidateSet->empty() ||
10771 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) ==
10772 OR_No_Viable_Function) {
10773 // In Microsoft mode, if we are inside a template class member function then
10774 // create a type dependent CallExpr. The goal is to postpone name lookup
10775 // to instantiation time to be able to search into type dependent base
10776 // classes.
10777 CallExpr *CE = new (Context) CallExpr(
10778 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010779 CE->setTypeDependent(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010780 *Result = CE;
Sam Panzer0f384432012-08-21 00:52:01 +000010781 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010782 }
Francois Pichetbcf64712011-09-07 00:14:57 +000010783 }
John McCalld681c392009-12-16 08:11:27 +000010784
Hans Wennborg64937c62015-06-11 21:21:57 +000010785 if (CandidateSet->empty())
10786 return false;
10787
John McCall4124c492011-10-17 18:40:02 +000010788 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000010789 return false;
10790}
John McCall4124c492011-10-17 18:40:02 +000010791
Sam Panzer0f384432012-08-21 00:52:01 +000010792/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10793/// the completed call expression. If overload resolution fails, emits
10794/// diagnostics and returns ExprError()
10795static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10796 UnresolvedLookupExpr *ULE,
10797 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010798 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010799 SourceLocation RParenLoc,
10800 Expr *ExecConfig,
10801 OverloadCandidateSet *CandidateSet,
10802 OverloadCandidateSet::iterator *Best,
10803 OverloadingResult OverloadResult,
10804 bool AllowTypoCorrection) {
10805 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010806 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010807 RParenLoc, /*EmptyLookup=*/true,
10808 AllowTypoCorrection);
10809
10810 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000010811 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000010812 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000010813 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000010814 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10815 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000010816 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010817 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10818 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000010819 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010820
Richard Smith998a5912011-06-05 22:42:48 +000010821 case OR_No_Viable_Function: {
10822 // Try to recover by looking for viable functions which the user might
10823 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000010824 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010825 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010826 /*EmptyLookup=*/false,
10827 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000010828 if (!Recovery.isInvalid())
10829 return Recovery;
10830
Sam Panzer0f384432012-08-21 00:52:01 +000010831 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010832 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +000010833 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010834 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010835 break;
Richard Smith998a5912011-06-05 22:42:48 +000010836 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010837
10838 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000010839 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000010840 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010841 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010842 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000010843
Sam Panzer0f384432012-08-21 00:52:01 +000010844 case OR_Deleted: {
10845 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10846 << (*Best)->Function->isDeleted()
10847 << ULE->getName()
10848 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10849 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010850 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000010851
Sam Panzer0f384432012-08-21 00:52:01 +000010852 // We emitted an error for the unvailable/deleted function call but keep
10853 // the call in the AST.
10854 FunctionDecl *FDecl = (*Best)->Function;
10855 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010856 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10857 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000010858 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010859 }
10860
Douglas Gregorb412e172010-07-25 18:17:45 +000010861 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000010862 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010863}
10864
Sam Panzer0f384432012-08-21 00:52:01 +000010865/// BuildOverloadedCallExpr - Given the call expression that calls Fn
10866/// (which eventually refers to the declaration Func) and the call
10867/// arguments Args/NumArgs, attempt to resolve the function call down
10868/// to a specific function. If overload resolution succeeds, returns
10869/// the call expression produced by overload resolution.
10870/// Otherwise, emits diagnostics and returns ExprError.
10871ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10872 UnresolvedLookupExpr *ULE,
10873 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010874 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010875 SourceLocation RParenLoc,
10876 Expr *ExecConfig,
10877 bool AllowTypoCorrection) {
Richard Smith100b24a2014-04-17 01:52:14 +000010878 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
10879 OverloadCandidateSet::CSK_Normal);
Sam Panzer0f384432012-08-21 00:52:01 +000010880 ExprResult result;
10881
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010882 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10883 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000010884 return result;
10885
10886 OverloadCandidateSet::iterator Best;
10887 OverloadingResult OverloadResult =
10888 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10889
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010890 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010891 RParenLoc, ExecConfig, &CandidateSet,
10892 &Best, OverloadResult,
10893 AllowTypoCorrection);
10894}
10895
John McCall4c4c1df2010-01-26 03:27:55 +000010896static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000010897 return Functions.size() > 1 ||
10898 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10899}
10900
Douglas Gregor084d8552009-03-13 23:49:33 +000010901/// \brief Create a unary operation that may resolve to an overloaded
10902/// operator.
10903///
10904/// \param OpLoc The location of the operator itself (e.g., '*').
10905///
10906/// \param OpcIn The UnaryOperator::Opcode that describes this
10907/// operator.
10908///
James Dennett18348b62012-06-22 08:52:37 +000010909/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000010910/// considered by overload resolution. The caller needs to build this
10911/// set based on the context using, e.g.,
10912/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10913/// set should not contain any member functions; those will be added
10914/// by CreateOverloadedUnaryOp().
10915///
James Dennett91738ff2012-06-22 10:32:46 +000010916/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000010917ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +000010918Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10919 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +000010920 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010921 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +000010922
10923 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10924 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10925 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010926 // TODO: provide better source location info.
10927 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000010928
John McCall4124c492011-10-17 18:40:02 +000010929 if (checkPlaceholderForOverload(*this, Input))
10930 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010931
Craig Topperc3ec1492014-05-26 06:22:03 +000010932 Expr *Args[2] = { Input, nullptr };
Douglas Gregor084d8552009-03-13 23:49:33 +000010933 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000010934
Douglas Gregor084d8552009-03-13 23:49:33 +000010935 // For post-increment and post-decrement, add the implicit '0' as
10936 // the second argument, so that we know this is a post-increment or
10937 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000010938 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010939 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000010940 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10941 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000010942 NumArgs = 2;
10943 }
10944
Richard Smithe54c3072013-05-05 15:51:06 +000010945 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10946
Douglas Gregor084d8552009-03-13 23:49:33 +000010947 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000010948 if (Fns.empty())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010949 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
10950 VK_RValue, OK_Ordinary, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010951
Craig Topperc3ec1492014-05-26 06:22:03 +000010952 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000010953 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000010954 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000010955 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010956 /*ADL*/ true, IsOverloaded(Fns),
10957 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010958 return new (Context)
10959 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
10960 VK_RValue, OpLoc, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000010961 }
10962
10963 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000010964 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor084d8552009-03-13 23:49:33 +000010965
10966 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000010967 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010968
10969 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000010970 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010971
John McCall4c4c1df2010-01-26 03:27:55 +000010972 // Add candidates from ADL.
Richard Smith100b24a2014-04-17 01:52:14 +000010973 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
Craig Topperc3ec1492014-05-26 06:22:03 +000010974 /*ExplicitTemplateArgs*/nullptr,
10975 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000010976
Douglas Gregor084d8552009-03-13 23:49:33 +000010977 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000010978 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010979
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010980 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10981
Douglas Gregor084d8552009-03-13 23:49:33 +000010982 // Perform overload resolution.
10983 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010984 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010985 case OR_Success: {
10986 // We found a built-in operator or an overloaded operator.
10987 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000010988
Douglas Gregor084d8552009-03-13 23:49:33 +000010989 if (FnDecl) {
10990 // We matched an overloaded operator. Build a call to that
10991 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000010992
Douglas Gregor084d8552009-03-13 23:49:33 +000010993 // Convert the arguments.
10994 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Craig Topperc3ec1492014-05-26 06:22:03 +000010995 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000010996
John Wiegley01296292011-04-08 18:41:53 +000010997 ExprResult InputRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000010998 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000010999 Best->FoundDecl, Method);
11000 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011001 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011002 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011003 } else {
11004 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011005 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000011006 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011007 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000011008 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011009 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000011010 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000011011 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000011012 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011013 Input = InputInit.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011014 }
11015
Douglas Gregor084d8552009-03-13 23:49:33 +000011016 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000011017 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011018 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011019 if (FnExpr.isInvalid())
11020 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000011021
Richard Smithc1564702013-11-15 02:58:23 +000011022 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011023 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011024 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11025 ResultTy = ResultTy.getNonLValueExprType(Context);
11026
Eli Friedman030eee42009-11-18 03:58:17 +000011027 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000011028 CallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011029 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
Lang Hames5de91cc2012-10-02 04:45:10 +000011030 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000011031
Alp Toker314cc812014-01-25 16:55:45 +000011032 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000011033 return ExprError();
11034
John McCallb268a282010-08-23 23:25:46 +000011035 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000011036 } else {
11037 // We matched a built-in operator. Convert the arguments, then
11038 // break out so that we will build the appropriate built-in
11039 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011040 ExprResult InputRes =
11041 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
11042 Best->Conversions[0], AA_Passing);
11043 if (InputRes.isInvalid())
11044 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011045 Input = InputRes.get();
Douglas Gregor084d8552009-03-13 23:49:33 +000011046 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000011047 }
John Wiegley01296292011-04-08 18:41:53 +000011048 }
11049
11050 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000011051 // This is an erroneous use of an operator which can be overloaded by
11052 // a non-member function. Check for non-member operators which were
11053 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011054 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000011055 // FIXME: Recover by calling the found function.
11056 return ExprError();
11057
John Wiegley01296292011-04-08 18:41:53 +000011058 // No viable function; fall through to handling this as a
11059 // built-in operator, which will produce an error message for us.
11060 break;
11061
11062 case OR_Ambiguous:
11063 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11064 << UnaryOperator::getOpcodeStr(Opc)
11065 << Input->getType()
11066 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011067 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000011068 UnaryOperator::getOpcodeStr(Opc), OpLoc);
11069 return ExprError();
11070
11071 case OR_Deleted:
11072 Diag(OpLoc, diag::err_ovl_deleted_oper)
11073 << Best->Function->isDeleted()
11074 << UnaryOperator::getOpcodeStr(Opc)
11075 << getDeletedOrUnavailableSuffix(Best->Function)
11076 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000011077 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011078 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011079 return ExprError();
11080 }
Douglas Gregor084d8552009-03-13 23:49:33 +000011081
11082 // Either we found no viable overloaded operator or we matched a
11083 // built-in operator. In either case, fall through to trying to
11084 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000011085 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000011086}
11087
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011088/// \brief Create a binary operation that may resolve to an overloaded
11089/// operator.
11090///
11091/// \param OpLoc The location of the operator itself (e.g., '+').
11092///
11093/// \param OpcIn The BinaryOperator::Opcode that describes this
11094/// operator.
11095///
James Dennett18348b62012-06-22 08:52:37 +000011096/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011097/// considered by overload resolution. The caller needs to build this
11098/// set based on the context using, e.g.,
11099/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
11100/// set should not contain any member functions; those will be added
11101/// by CreateOverloadedBinOp().
11102///
11103/// \param LHS Left-hand argument.
11104/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000011105ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011106Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +000011107 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +000011108 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011109 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011110 Expr *Args[2] = { LHS, RHS };
Craig Topperc3ec1492014-05-26 06:22:03 +000011111 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011112
11113 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
11114 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
11115 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
11116
11117 // If either side is type-dependent, create an appropriate dependent
11118 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000011119 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000011120 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011121 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000011122 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000011123 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011124 return new (Context) BinaryOperator(
11125 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
11126 OpLoc, FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011127
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011128 return new (Context) CompoundAssignOperator(
11129 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
11130 Context.DependentTy, Context.DependentTy, OpLoc,
11131 FPFeatures.fp_contract);
Douglas Gregor5287f092009-11-05 00:51:44 +000011132 }
John McCall4c4c1df2010-01-26 03:27:55 +000011133
11134 // FIXME: save results of ADL from here?
Craig Topperc3ec1492014-05-26 06:22:03 +000011135 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011136 // TODO: provide better source location info in DNLoc component.
11137 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000011138 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000011139 = UnresolvedLookupExpr::Create(Context, NamingClass,
11140 NestedNameSpecifierLoc(), OpNameInfo,
11141 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011142 Fns.begin(), Fns.end());
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011143 return new (Context)
11144 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
11145 VK_RValue, OpLoc, FPFeatures.fp_contract);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011146 }
11147
John McCall4124c492011-10-17 18:40:02 +000011148 // Always do placeholder-like conversions on the RHS.
11149 if (checkPlaceholderForOverload(*this, Args[1]))
11150 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011151
John McCall526ab472011-10-25 17:37:35 +000011152 // Do placeholder-like conversion on the LHS; note that we should
11153 // not get here with a PseudoObject LHS.
11154 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000011155 if (checkPlaceholderForOverload(*this, Args[0]))
11156 return ExprError();
11157
Sebastian Redl6a96bf72009-11-18 23:10:33 +000011158 // If this is the assignment operator, we only perform overload resolution
11159 // if the left-hand side is a class or enumeration type. This is actually
11160 // a hack. The standard requires that we do overload resolution between the
11161 // various built-in candidates, but as DR507 points out, this can lead to
11162 // problems. So we do it this way, which pretty much follows what GCC does.
11163 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000011164 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000011165 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011166
John McCalle26a8722010-12-04 08:14:53 +000011167 // If this is the .* operator, which is not overloadable, just
11168 // create a built-in binary operator.
11169 if (Opc == BO_PtrMemD)
11170 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11171
Douglas Gregor084d8552009-03-13 23:49:33 +000011172 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011173 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011174
11175 // Add the candidates from the given function set.
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000011176 AddFunctionCandidates(Fns, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011177
11178 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011179 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011180
Richard Smith0daabd72014-09-23 20:31:39 +000011181 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
11182 // performed for an assignment operator (nor for operator[] nor operator->,
11183 // which don't get here).
11184 if (Opc != BO_Assign)
11185 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
11186 /*ExplicitTemplateArgs*/ nullptr,
11187 CandidateSet);
John McCall4c4c1df2010-01-26 03:27:55 +000011188
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011189 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011190 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011191
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011192 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11193
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011194 // Perform overload resolution.
11195 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011196 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000011197 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011198 // We found a built-in operator or an overloaded operator.
11199 FunctionDecl *FnDecl = Best->Function;
11200
11201 if (FnDecl) {
11202 // We matched an overloaded operator. Build a call to that
11203 // operator.
11204
11205 // Convert the arguments.
11206 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000011207 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000011208 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000011209
Chandler Carruth8e543b32010-12-12 08:17:55 +000011210 ExprResult Arg1 =
11211 PerformCopyInitialization(
11212 InitializedEntity::InitializeParameter(Context,
11213 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011214 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011215 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011216 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011217
John Wiegley01296292011-04-08 18:41:53 +000011218 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011219 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011220 Best->FoundDecl, Method);
11221 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011222 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011223 Args[0] = Arg0.getAs<Expr>();
11224 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011225 } else {
11226 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000011227 ExprResult Arg0 = PerformCopyInitialization(
11228 InitializedEntity::InitializeParameter(Context,
11229 FnDecl->getParamDecl(0)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011230 SourceLocation(), Args[0]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011231 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011232 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011233
Chandler Carruth8e543b32010-12-12 08:17:55 +000011234 ExprResult Arg1 =
11235 PerformCopyInitialization(
11236 InitializedEntity::InitializeParameter(Context,
11237 FnDecl->getParamDecl(1)),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011238 SourceLocation(), Args[1]);
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000011239 if (Arg1.isInvalid())
11240 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011241 Args[0] = LHS = Arg0.getAs<Expr>();
11242 Args[1] = RHS = Arg1.getAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011243 }
11244
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011245 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011246 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011247 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011248 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011249 if (FnExpr.isInvalid())
11250 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011251
Richard Smithc1564702013-11-15 02:58:23 +000011252 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000011253 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011254 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11255 ResultTy = ResultTy.getNonLValueExprType(Context);
11256
John McCallb268a282010-08-23 23:25:46 +000011257 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011258 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000011259 Args, ResultTy, VK, OpLoc,
11260 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011261
Alp Toker314cc812014-01-25 16:55:45 +000011262 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011263 FnDecl))
11264 return ExprError();
11265
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011266 ArrayRef<const Expr *> ArgsArray(Args, 2);
11267 // Cut off the implicit 'this'.
11268 if (isa<CXXMethodDecl>(FnDecl))
11269 ArgsArray = ArgsArray.slice(1);
Richard Trieu36d0b2b2015-01-13 02:32:02 +000011270
11271 // Check for a self move.
11272 if (Op == OO_Equal)
11273 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
11274
Douglas Gregorb4866e82015-06-19 18:13:19 +000011275 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc,
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000011276 TheCall->getSourceRange(), VariadicDoesNotApply);
11277
John McCallb268a282010-08-23 23:25:46 +000011278 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011279 } else {
11280 // We matched a built-in operator. Convert the arguments, then
11281 // break out so that we will build the appropriate built-in
11282 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011283 ExprResult ArgsRes0 =
11284 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11285 Best->Conversions[0], AA_Passing);
11286 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011287 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011288 Args[0] = ArgsRes0.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011289
John Wiegley01296292011-04-08 18:41:53 +000011290 ExprResult ArgsRes1 =
11291 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11292 Best->Conversions[1], AA_Passing);
11293 if (ArgsRes1.isInvalid())
11294 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011295 Args[1] = ArgsRes1.get();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011296 break;
11297 }
11298 }
11299
Douglas Gregor66950a32009-09-30 21:46:01 +000011300 case OR_No_Viable_Function: {
11301 // C++ [over.match.oper]p9:
11302 // If the operator is the operator , [...] and there are no
11303 // viable functions, then the operator is assumed to be the
11304 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000011305 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000011306 break;
11307
Chandler Carruth8e543b32010-12-12 08:17:55 +000011308 // For class as left operand for assignment or compound assigment
11309 // operator do not fall through to handling in built-in, but report that
11310 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000011311 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011312 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000011313 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000011314 Diag(OpLoc, diag::err_ovl_no_viable_oper)
11315 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000011316 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000011317 if (Args[0]->getType()->isIncompleteType()) {
11318 Diag(OpLoc, diag::note_assign_lhs_incomplete)
11319 << Args[0]->getType()
11320 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11321 }
Douglas Gregor66950a32009-09-30 21:46:01 +000011322 } else {
Richard Smith998a5912011-06-05 22:42:48 +000011323 // This is an erroneous use of an operator which can be overloaded by
11324 // a non-member function. Check for non-member operators which were
11325 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011326 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000011327 // FIXME: Recover by calling the found function.
11328 return ExprError();
11329
Douglas Gregor66950a32009-09-30 21:46:01 +000011330 // No viable function; try to create a built-in operation, which will
11331 // produce an error. Then, show the non-viable candidates.
11332 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000011333 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011334 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000011335 "C++ binary operator overloading is missing candidates!");
11336 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011337 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011338 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011339 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000011340 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011341
11342 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011343 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011344 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000011345 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000011346 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011347 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011348 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011349 return ExprError();
11350
11351 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000011352 if (isImplicitlyDeleted(Best->Function)) {
11353 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11354 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000011355 << Context.getRecordType(Method->getParent())
11356 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000011357
Richard Smithde1a4872012-12-28 12:23:24 +000011358 // The user probably meant to call this special member. Just
11359 // explain why it's deleted.
11360 NoteDeletedFunction(Method);
11361 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000011362 } else {
11363 Diag(OpLoc, diag::err_ovl_deleted_oper)
11364 << Best->Function->isDeleted()
11365 << BinaryOperator::getOpcodeStr(Opc)
11366 << getDeletedOrUnavailableSuffix(Best->Function)
11367 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11368 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011369 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011370 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011371 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000011372 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011373
Douglas Gregor66950a32009-09-30 21:46:01 +000011374 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000011375 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011376}
11377
John McCalldadc5752010-08-24 06:29:42 +000011378ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000011379Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11380 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000011381 Expr *Base, Expr *Idx) {
11382 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000011383 DeclarationName OpName =
11384 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11385
11386 // If either side is type-dependent, create an appropriate dependent
11387 // expression.
11388 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11389
Craig Topperc3ec1492014-05-26 06:22:03 +000011390 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011391 // CHECKME: no 'operator' keyword?
11392 DeclarationNameInfo OpNameInfo(OpName, LLoc);
11393 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000011394 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011395 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011396 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011397 /*ADL*/ true, /*Overloaded*/ false,
11398 UnresolvedSetIterator(),
11399 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000011400 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000011401
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011402 return new (Context)
11403 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11404 Context.DependentTy, VK_RValue, RLoc, false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011405 }
11406
John McCall4124c492011-10-17 18:40:02 +000011407 // Handle placeholders on both operands.
11408 if (checkPlaceholderForOverload(*this, Args[0]))
11409 return ExprError();
11410 if (checkPlaceholderForOverload(*this, Args[1]))
11411 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011412
Sebastian Redladba46e2009-10-29 20:17:01 +000011413 // Build an empty overload set.
Richard Smith100b24a2014-04-17 01:52:14 +000011414 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
Sebastian Redladba46e2009-10-29 20:17:01 +000011415
11416 // Subscript can only be overloaded as a member function.
11417
11418 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011419 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011420
11421 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011422 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011423
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011424 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11425
Sebastian Redladba46e2009-10-29 20:17:01 +000011426 // Perform overload resolution.
11427 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011428 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000011429 case OR_Success: {
11430 // We found a built-in operator or an overloaded operator.
11431 FunctionDecl *FnDecl = Best->Function;
11432
11433 if (FnDecl) {
11434 // We matched an overloaded operator. Build a call to that
11435 // operator.
11436
John McCalla0296f72010-03-19 07:35:19 +000011437 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000011438
Sebastian Redladba46e2009-10-29 20:17:01 +000011439 // Convert the arguments.
11440 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000011441 ExprResult Arg0 =
Craig Topperc3ec1492014-05-26 06:22:03 +000011442 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000011443 Best->FoundDecl, Method);
11444 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011445 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011446 Args[0] = Arg0.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011447
Anders Carlssona68e51e2010-01-29 18:37:50 +000011448 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011449 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000011450 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011451 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000011452 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011453 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011454 Args[1]);
Anders Carlssona68e51e2010-01-29 18:37:50 +000011455 if (InputInit.isInvalid())
11456 return ExprError();
11457
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011458 Args[1] = InputInit.getAs<Expr>();
Anders Carlssona68e51e2010-01-29 18:37:50 +000011459
Sebastian Redladba46e2009-10-29 20:17:01 +000011460 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011461 DeclarationNameInfo OpLocInfo(OpName, LLoc);
11462 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011463 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011464 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011465 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011466 OpLocInfo.getLoc(),
11467 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011468 if (FnExpr.isInvalid())
11469 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011470
Richard Smithc1564702013-11-15 02:58:23 +000011471 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000011472 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011473 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11474 ResultTy = ResultTy.getNonLValueExprType(Context);
11475
John McCallb268a282010-08-23 23:25:46 +000011476 CXXOperatorCallExpr *TheCall =
11477 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011478 FnExpr.get(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000011479 ResultTy, VK, RLoc,
11480 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011481
Alp Toker314cc812014-01-25 16:55:45 +000011482 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000011483 return ExprError();
11484
John McCallb268a282010-08-23 23:25:46 +000011485 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000011486 } else {
11487 // We matched a built-in operator. Convert the arguments, then
11488 // break out so that we will build the appropriate built-in
11489 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011490 ExprResult ArgsRes0 =
11491 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11492 Best->Conversions[0], AA_Passing);
11493 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011494 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011495 Args[0] = ArgsRes0.get();
John Wiegley01296292011-04-08 18:41:53 +000011496
11497 ExprResult ArgsRes1 =
11498 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11499 Best->Conversions[1], AA_Passing);
11500 if (ArgsRes1.isInvalid())
11501 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011502 Args[1] = ArgsRes1.get();
Sebastian Redladba46e2009-10-29 20:17:01 +000011503
11504 break;
11505 }
11506 }
11507
11508 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000011509 if (CandidateSet.empty())
11510 Diag(LLoc, diag::err_ovl_no_oper)
11511 << Args[0]->getType() << /*subscript*/ 0
11512 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11513 else
11514 Diag(LLoc, diag::err_ovl_no_viable_subscript)
11515 << Args[0]->getType()
11516 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011517 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011518 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000011519 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011520 }
11521
11522 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011523 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011524 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000011525 << Args[0]->getType() << Args[1]->getType()
11526 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011527 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011528 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011529 return ExprError();
11530
11531 case OR_Deleted:
11532 Diag(LLoc, diag::err_ovl_deleted_oper)
11533 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011534 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000011535 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011536 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011537 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011538 return ExprError();
11539 }
11540
11541 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000011542 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011543}
11544
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011545/// BuildCallToMemberFunction - Build a call to a member
11546/// function. MemExpr is the expression that refers to the member
11547/// function (and includes the object parameter), Args/NumArgs are the
11548/// arguments to the function call (not including the object
11549/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000011550/// expression refers to a non-static member function or an overloaded
11551/// member function.
John McCalldadc5752010-08-24 06:29:42 +000011552ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000011553Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011554 SourceLocation LParenLoc,
11555 MultiExprArg Args,
11556 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000011557 assert(MemExprE->getType() == Context.BoundMemberTy ||
11558 MemExprE->getType() == Context.OverloadTy);
11559
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011560 // Dig out the member expression. This holds both the object
11561 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000011562 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011563
John McCall0009fcc2011-04-26 20:42:42 +000011564 // Determine whether this is a call to a pointer-to-member function.
11565 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11566 assert(op->getType() == Context.BoundMemberTy);
11567 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
11568
11569 QualType fnType =
11570 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11571
11572 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11573 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000011574 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000011575
11576 // Check that the object type isn't more qualified than the
11577 // member function we're calling.
11578 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11579
11580 QualType objectType = op->getLHS()->getType();
11581 if (op->getOpcode() == BO_PtrMemI)
11582 objectType = objectType->castAs<PointerType>()->getPointeeType();
11583 Qualifiers objectQuals = objectType.getQualifiers();
11584
11585 Qualifiers difference = objectQuals - funcQuals;
11586 difference.removeObjCGCAttr();
11587 difference.removeAddressSpace();
11588 if (difference) {
11589 std::string qualsString = difference.getAsString();
11590 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11591 << fnType.getUnqualifiedType()
11592 << qualsString
11593 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11594 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011595
John McCall0009fcc2011-04-26 20:42:42 +000011596 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011597 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000011598 resultType, valueKind, RParenLoc);
11599
Alp Toker314cc812014-01-25 16:55:45 +000011600 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
Craig Topperc3ec1492014-05-26 06:22:03 +000011601 call, nullptr))
John McCall0009fcc2011-04-26 20:42:42 +000011602 return ExprError();
11603
Craig Topperc3ec1492014-05-26 06:22:03 +000011604 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000011605 return ExprError();
11606
Richard Trieu9be9c682013-06-22 02:30:38 +000011607 if (CheckOtherCall(call, proto))
11608 return ExprError();
11609
John McCall0009fcc2011-04-26 20:42:42 +000011610 return MaybeBindToTemporary(call);
11611 }
11612
David Majnemerced8bdf2015-02-25 17:36:15 +000011613 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
11614 return new (Context)
11615 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc);
11616
John McCall4124c492011-10-17 18:40:02 +000011617 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011618 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000011619 return ExprError();
11620
John McCall10eae182009-11-30 22:42:35 +000011621 MemberExpr *MemExpr;
Craig Topperc3ec1492014-05-26 06:22:03 +000011622 CXXMethodDecl *Method = nullptr;
11623 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
11624 NestedNameSpecifier *Qualifier = nullptr;
John McCall10eae182009-11-30 22:42:35 +000011625 if (isa<MemberExpr>(NakedMemExpr)) {
11626 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000011627 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000011628 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011629 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000011630 UnbridgedCasts.restore();
Nick Lewyckye283c552015-08-25 22:33:16 +000011631
11632 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
11633 Diag(MemExprE->getLocStart(),
11634 diag::err_ovl_no_viable_member_function_in_call)
11635 << Method << Method->getSourceRange();
11636 Diag(Method->getLocation(),
11637 diag::note_ovl_candidate_disabled_by_enable_if_attr)
11638 << Attr->getCond()->getSourceRange() << Attr->getMessage();
11639 return ExprError();
11640 }
John McCall10eae182009-11-30 22:42:35 +000011641 } else {
11642 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011643 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011644
John McCall6e9f8f62009-12-03 04:06:58 +000011645 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000011646 Expr::Classification ObjectClassification
11647 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11648 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000011649
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011650 // Add overload candidates
Richard Smith100b24a2014-04-17 01:52:14 +000011651 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
11652 OverloadCandidateSet::CSK_Normal);
Mike Stump11289f42009-09-09 15:08:12 +000011653
John McCall2d74de92009-12-01 22:10:20 +000011654 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000011655 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000011656 if (UnresExpr->hasExplicitTemplateArgs()) {
11657 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11658 TemplateArgs = &TemplateArgsBuffer;
11659 }
11660
John McCall10eae182009-11-30 22:42:35 +000011661 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11662 E = UnresExpr->decls_end(); I != E; ++I) {
11663
John McCall6e9f8f62009-12-03 04:06:58 +000011664 NamedDecl *Func = *I;
11665 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11666 if (isa<UsingShadowDecl>(Func))
11667 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11668
Douglas Gregor02824322011-01-26 19:30:28 +000011669
Francois Pichet64225792011-01-18 05:04:39 +000011670 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011671 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011672 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011673 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000011674 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000011675 // If explicit template arguments were provided, we can't call a
11676 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000011677 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000011678 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011679
John McCalla0296f72010-03-19 07:35:19 +000011680 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011681 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000011682 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000011683 } else {
John McCall10eae182009-11-30 22:42:35 +000011684 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000011685 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011686 ObjectType, ObjectClassification,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011687 Args, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000011688 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000011689 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000011690 }
Mike Stump11289f42009-09-09 15:08:12 +000011691
John McCall10eae182009-11-30 22:42:35 +000011692 DeclarationName DeclName = UnresExpr->getMemberName();
11693
John McCall4124c492011-10-17 18:40:02 +000011694 UnbridgedCasts.restore();
11695
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011696 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011697 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000011698 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011699 case OR_Success:
11700 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000011701 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000011702 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011703 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11704 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000011705 // If FoundDecl is different from Method (such as if one is a template
11706 // and the other a specialization), make sure DiagnoseUseOfDecl is
11707 // called on both.
11708 // FIXME: This would be more comprehensively addressed by modifying
11709 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11710 // being used.
11711 if (Method != FoundDecl.getDecl() &&
11712 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11713 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011714 break;
11715
11716 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000011717 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011718 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000011719 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011720 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011721 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011722 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011723
11724 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000011725 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000011726 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011727 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011728 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011729 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000011730
11731 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000011732 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000011733 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011734 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011735 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011736 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011737 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000011738 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011739 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011740 }
11741
John McCall16df1e52010-03-30 21:47:33 +000011742 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000011743
John McCall2d74de92009-12-01 22:10:20 +000011744 // If overload resolution picked a static member, build a
11745 // non-member call based on that function.
11746 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011747 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11748 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000011749 }
11750
John McCall10eae182009-11-30 22:42:35 +000011751 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011752 }
11753
Alp Toker314cc812014-01-25 16:55:45 +000011754 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000011755 ExprValueKind VK = Expr::getValueKindForType(ResultType);
11756 ResultType = ResultType.getNonLValueExprType(Context);
11757
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011758 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011759 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011760 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000011761 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011762
Eli Bendersky291a57e2014-09-25 23:59:08 +000011763 // (CUDA B.1): Check for invalid calls between targets.
11764 if (getLangOpts().CUDA) {
11765 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) {
11766 if (CheckCUDATarget(Caller, Method)) {
11767 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target)
11768 << IdentifyCUDATarget(Method) << Method->getIdentifier()
11769 << IdentifyCUDATarget(Caller);
11770 return ExprError();
11771 }
11772 }
11773 }
11774
Anders Carlssonc4859ba2009-10-10 00:06:20 +000011775 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000011776 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000011777 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000011778 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011779
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011780 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000011781 // We only need to do this if there was actually an overload; otherwise
11782 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000011783 if (!Method->isStatic()) {
11784 ExprResult ObjectArg =
11785 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11786 FoundDecl, Method);
11787 if (ObjectArg.isInvalid())
11788 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011789 MemExpr->setBase(ObjectArg.get());
John Wiegley01296292011-04-08 18:41:53 +000011790 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011791
11792 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000011793 const FunctionProtoType *Proto =
11794 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011795 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011796 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000011797 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011798
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011799 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011800
Richard Smith55ce3522012-06-25 20:30:08 +000011801 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000011802 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000011803
Anders Carlsson47061ee2011-05-06 14:25:31 +000011804 if ((isa<CXXConstructorDecl>(CurContext) ||
11805 isa<CXXDestructorDecl>(CurContext)) &&
11806 TheCall->getMethodDecl()->isPure()) {
11807 const CXXMethodDecl *MD = TheCall->getMethodDecl();
11808
Davide Italianoccb37382015-07-14 23:36:10 +000011809 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
11810 MemExpr->performsVirtualDispatch(getLangOpts())) {
11811 Diag(MemExpr->getLocStart(),
Anders Carlsson47061ee2011-05-06 14:25:31 +000011812 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11813 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11814 << MD->getParent()->getDeclName();
11815
11816 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Davide Italianoccb37382015-07-14 23:36:10 +000011817 if (getLangOpts().AppleKext)
11818 Diag(MemExpr->getLocStart(),
11819 diag::note_pure_qualified_call_kext)
11820 << MD->getParent()->getDeclName()
11821 << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000011822 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000011823 }
John McCallb268a282010-08-23 23:25:46 +000011824 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011825}
11826
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011827/// BuildCallToObjectOfClassType - Build a call to an object of class
11828/// type (C++ [over.call.object]), which can end up invoking an
11829/// overloaded function call operator (@c operator()) or performing a
11830/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000011831ExprResult
John Wiegley01296292011-04-08 18:41:53 +000011832Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000011833 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011834 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011835 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000011836 if (checkPlaceholderForOverload(*this, Obj))
11837 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011838 ExprResult Object = Obj;
John McCall4124c492011-10-17 18:40:02 +000011839
11840 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011841 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000011842 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011843
Nico Weberb58e51c2014-11-19 05:21:39 +000011844 assert(Object.get()->getType()->isRecordType() &&
11845 "Requires object type argument");
John Wiegley01296292011-04-08 18:41:53 +000011846 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000011847
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011848 // C++ [over.call.object]p1:
11849 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000011850 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011851 // candidate functions includes at least the function call
11852 // operators of T. The function call operators of T are obtained by
11853 // ordinary lookup of the name operator() in the context of
11854 // (E).operator().
Richard Smith100b24a2014-04-17 01:52:14 +000011855 OverloadCandidateSet CandidateSet(LParenLoc,
11856 OverloadCandidateSet::CSK_Operator);
Douglas Gregor91f84212008-12-11 16:49:14 +000011857 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011858
John Wiegley01296292011-04-08 18:41:53 +000011859 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011860 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011861 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011862
John McCall27b18f82009-11-17 02:14:36 +000011863 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11864 LookupQualifiedName(R, Record->getDecl());
11865 R.suppressDiagnostics();
11866
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011867 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000011868 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000011869 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011870 Object.get()->Classify(Context),
11871 Args, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000011872 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000011873 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011874
Douglas Gregorab7897a2008-11-19 22:57:39 +000011875 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011876 // In addition, for each (non-explicit in C++0x) conversion function
11877 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000011878 //
11879 // operator conversion-type-id () cv-qualifier;
11880 //
11881 // where cv-qualifier is the same cv-qualification as, or a
11882 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000011883 // denotes the type "pointer to function of (P1,...,Pn) returning
11884 // R", or the type "reference to pointer to function of
11885 // (P1,...,Pn) returning R", or the type "reference to function
11886 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000011887 // is also considered as a candidate function. Similarly,
11888 // surrogate call functions are added to the set of candidate
11889 // functions for each conversion function declared in an
11890 // accessible base class provided the function is not hidden
11891 // within T by another intervening declaration.
Benjamin Kramerb4ef6682015-02-06 17:25:10 +000011892 const auto &Conversions =
11893 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
11894 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000011895 NamedDecl *D = *I;
11896 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11897 if (isa<UsingShadowDecl>(D))
11898 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011899
Douglas Gregor74ba25c2009-10-21 06:18:39 +000011900 // Skip over templated conversion functions; they aren't
11901 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000011902 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000011903 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000011904
John McCall6e9f8f62009-12-03 04:06:58 +000011905 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011906 if (!Conv->isExplicit()) {
11907 // Strip the reference type (if any) and then the pointer type (if
11908 // any) to get down to what might be a function type.
11909 QualType ConvType = Conv->getConversionType().getNonReferenceType();
11910 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11911 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000011912
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011913 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11914 {
11915 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011916 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011917 }
11918 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000011919 }
Mike Stump11289f42009-09-09 15:08:12 +000011920
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011921 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11922
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011923 // Perform overload resolution.
11924 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000011925 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000011926 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011927 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000011928 // Overload resolution succeeded; we'll build the appropriate call
11929 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011930 break;
11931
11932 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000011933 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011934 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000011935 << Object.get()->getType() << /*call*/ 1
11936 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000011937 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011938 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000011939 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000011940 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011941 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011942 break;
11943
11944 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011945 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011946 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000011947 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011948 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011949 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011950
11951 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011952 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000011953 diag::err_ovl_deleted_object_call)
11954 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000011955 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011956 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000011957 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011958 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000011959 break;
Mike Stump11289f42009-09-09 15:08:12 +000011960 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011961
Douglas Gregorb412e172010-07-25 18:17:45 +000011962 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011963 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011964
John McCall4124c492011-10-17 18:40:02 +000011965 UnbridgedCasts.restore();
11966
Craig Topperc3ec1492014-05-26 06:22:03 +000011967 if (Best->Function == nullptr) {
Douglas Gregorab7897a2008-11-19 22:57:39 +000011968 // Since there is no function declaration, this is one of the
11969 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000011970 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000011971 = cast<CXXConversionDecl>(
11972 Best->Conversions[0].UserDefined.ConversionFunction);
11973
Craig Topperc3ec1492014-05-26 06:22:03 +000011974 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
11975 Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011976 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11977 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000011978 assert(Conv == Best->FoundDecl.getDecl() &&
11979 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000011980 // We selected one of the surrogate functions that converts the
11981 // object parameter to a function pointer. Perform the conversion
11982 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011983
Fariborz Jahanian774cf792009-09-28 18:35:46 +000011984 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000011985 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011986 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11987 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000011988 if (Call.isInvalid())
11989 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000011990 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011991 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
11992 CK_UserDefinedConversion, Call.get(),
11993 nullptr, VK_RValue);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011994
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011995 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000011996 }
11997
Craig Topperc3ec1492014-05-26 06:22:03 +000011998 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000011999
Douglas Gregorab7897a2008-11-19 22:57:39 +000012000 // We found an overloaded operator(). Build a CXXOperatorCallExpr
12001 // that calls this method, using Object for the implicit object
12002 // parameter and passing along the remaining arguments.
12003 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000012004
12005 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000012006 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000012007 return ExprError();
12008
Chandler Carruth8e543b32010-12-12 08:17:55 +000012009 const FunctionProtoType *Proto =
12010 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012011
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012012 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000012013
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012014 DeclarationNameInfo OpLocInfo(
12015 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
12016 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000012017 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012018 HadMultipleCandidates,
12019 OpLocInfo.getLoc(),
12020 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000012021 if (NewFn.isInvalid())
12022 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012023
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012024 // Build the full argument list for the method call (the implicit object
12025 // parameter is placed at the beginning of the list).
Ahmed Charlesaf94d562014-03-09 11:34:25 +000012026 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012027 MethodArgs[0] = Object.get();
12028 std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
12029
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012030 // Once we've built TheCall, all of the expressions are properly
12031 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000012032 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012033 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12034 ResultTy = ResultTy.getNonLValueExprType(Context);
12035
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012036 CXXOperatorCallExpr *TheCall = new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012037 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000012038 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
12039 ResultTy, VK, RParenLoc, false);
12040 MethodArgs.reset();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012041
Alp Toker314cc812014-01-25 16:55:45 +000012042 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000012043 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012044
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012045 // We may have default arguments. If so, we need to allocate more
12046 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012047 if (Args.size() < NumParams)
12048 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012049
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012050 bool IsError = false;
12051
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012052 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000012053 ExprResult ObjRes =
Craig Topperc3ec1492014-05-26 06:22:03 +000012054 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012055 Best->FoundDecl, Method);
12056 if (ObjRes.isInvalid())
12057 IsError = true;
12058 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000012059 Object = ObjRes;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012060 TheCall->setArg(0, Object.get());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012061
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012062 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012063 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012064 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012065 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012066 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000012067
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012068 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012069
John McCalldadc5752010-08-24 06:29:42 +000012070 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012071 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000012072 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012073 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000012074 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012075
Anders Carlsson7c5fe482010-01-29 18:43:53 +000012076 IsError |= InputInit.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012077 Arg = InputInit.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012078 } else {
John McCalldadc5752010-08-24 06:29:42 +000012079 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000012080 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
12081 if (DefArg.isInvalid()) {
12082 IsError = true;
12083 break;
12084 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012085
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012086 Arg = DefArg.getAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000012087 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012088
12089 TheCall->setArg(i + 1, Arg);
12090 }
12091
12092 // If this is a variadic call, handle args passed through "...".
12093 if (Proto->isVariadic()) {
12094 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000012095 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
Craig Topperc3ec1492014-05-26 06:22:03 +000012096 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
12097 nullptr);
John Wiegley01296292011-04-08 18:41:53 +000012098 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012099 TheCall->setArg(i + 1, Arg.get());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012100 }
12101 }
12102
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000012103 if (IsError) return true;
12104
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000012105 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000012106
Richard Smith55ce3522012-06-25 20:30:08 +000012107 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000012108 return true;
12109
John McCalle172be52010-08-24 06:09:16 +000012110 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000012111}
12112
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012113/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000012114/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012115/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000012116ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012117Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
12118 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000012119 assert(Base->getType()->isRecordType() &&
12120 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000012121
John McCall4124c492011-10-17 18:40:02 +000012122 if (checkPlaceholderForOverload(*this, Base))
12123 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000012124
John McCallbc077cf2010-02-08 23:07:23 +000012125 SourceLocation Loc = Base->getExprLoc();
12126
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012127 // C++ [over.ref]p1:
12128 //
12129 // [...] An expression x->m is interpreted as (x.operator->())->m
12130 // for a class object x of type T if T::operator->() exists and if
12131 // the operator is selected as the best match function by the
12132 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000012133 DeclarationName OpName =
12134 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
Richard Smith100b24a2014-04-17 01:52:14 +000012135 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000012136 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000012137
John McCallbc077cf2010-02-08 23:07:23 +000012138 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000012139 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000012140 return ExprError();
12141
John McCall27b18f82009-11-17 02:14:36 +000012142 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
12143 LookupQualifiedName(R, BaseRecord->getDecl());
12144 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000012145
12146 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000012147 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000012148 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000012149 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000012150 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012151
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012152 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12153
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012154 // Perform overload resolution.
12155 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000012156 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012157 case OR_Success:
12158 // Overload resolution succeeded; we'll build the call below.
12159 break;
12160
12161 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012162 if (CandidateSet.empty()) {
12163 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000012164 if (NoArrowOperatorFound) {
12165 // Report this specific error to the caller instead of emitting a
12166 // diagnostic, as requested.
12167 *NoArrowOperatorFound = true;
12168 return ExprError();
12169 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012170 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
12171 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012172 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000012173 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012174 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000012175 }
12176 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012177 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000012178 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012179 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012180 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012181
12182 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000012183 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
12184 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012185 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012186 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000012187
12188 case OR_Deleted:
12189 Diag(OpLoc, diag::err_ovl_deleted_oper)
12190 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012191 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000012192 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000012193 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000012194 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000012195 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012196 }
12197
Craig Topperc3ec1492014-05-26 06:22:03 +000012198 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
John McCalla0296f72010-03-19 07:35:19 +000012199
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012200 // Convert the object parameter.
12201 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000012202 ExprResult BaseResult =
Craig Topperc3ec1492014-05-26 06:22:03 +000012203 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +000012204 Best->FoundDecl, Method);
12205 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000012206 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012207 Base = BaseResult.get();
Douglas Gregor9ecea262008-11-21 03:04:22 +000012208
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012209 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000012210 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000012211 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000012212 if (FnExpr.isInvalid())
12213 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012214
Alp Toker314cc812014-01-25 16:55:45 +000012215 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000012216 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12217 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000012218 CXXOperatorCallExpr *TheCall =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012219 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
Lang Hames5de91cc2012-10-02 04:45:10 +000012220 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012221
Alp Toker314cc812014-01-25 16:55:45 +000012222 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000012223 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000012224
12225 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000012226}
12227
Richard Smithbcc22fc2012-03-09 08:00:36 +000012228/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
12229/// a literal operator described by the provided lookup results.
12230ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
12231 DeclarationNameInfo &SuffixInfo,
12232 ArrayRef<Expr*> Args,
12233 SourceLocation LitEndLoc,
12234 TemplateArgumentListInfo *TemplateArgs) {
12235 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000012236
Richard Smith100b24a2014-04-17 01:52:14 +000012237 OverloadCandidateSet CandidateSet(UDSuffixLoc,
12238 OverloadCandidateSet::CSK_Normal);
Francisco Lopes da Silva975a9f62015-01-21 16:24:11 +000012239 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
12240 /*SuppressUserConversions=*/true);
Richard Smithc67fdd42012-03-07 08:35:16 +000012241
Richard Smithbcc22fc2012-03-09 08:00:36 +000012242 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12243
Richard Smithbcc22fc2012-03-09 08:00:36 +000012244 // Perform overload resolution. This will usually be trivial, but might need
12245 // to perform substitutions for a literal operator template.
12246 OverloadCandidateSet::iterator Best;
12247 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
12248 case OR_Success:
12249 case OR_Deleted:
12250 break;
12251
12252 case OR_No_Viable_Function:
12253 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
12254 << R.getLookupName();
12255 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
12256 return ExprError();
12257
12258 case OR_Ambiguous:
12259 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
12260 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
12261 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000012262 }
12263
Richard Smithbcc22fc2012-03-09 08:00:36 +000012264 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000012265 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
12266 HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000012267 SuffixInfo.getLoc(),
12268 SuffixInfo.getInfo());
12269 if (Fn.isInvalid())
12270 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000012271
12272 // Check the argument types. This should almost always be a no-op, except
12273 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000012274 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000012275 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000012276 ExprResult InputInit = PerformCopyInitialization(
12277 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12278 SourceLocation(), Args[ArgIdx]);
12279 if (InputInit.isInvalid())
12280 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012281 ConvArgs[ArgIdx] = InputInit.get();
Richard Smithc67fdd42012-03-07 08:35:16 +000012282 }
12283
Alp Toker314cc812014-01-25 16:55:45 +000012284 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000012285 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12286 ResultTy = ResultTy.getNonLValueExprType(Context);
12287
Richard Smithc67fdd42012-03-07 08:35:16 +000012288 UserDefinedLiteral *UDL =
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012289 new (Context) UserDefinedLiteral(Context, Fn.get(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000012290 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000012291 ResultTy, VK, LitEndLoc, UDSuffixLoc);
12292
Alp Toker314cc812014-01-25 16:55:45 +000012293 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000012294 return ExprError();
12295
Craig Topperc3ec1492014-05-26 06:22:03 +000012296 if (CheckFunctionCall(FD, UDL, nullptr))
Richard Smithc67fdd42012-03-07 08:35:16 +000012297 return ExprError();
12298
12299 return MaybeBindToTemporary(UDL);
12300}
12301
Sam Panzer0f384432012-08-21 00:52:01 +000012302/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12303/// given LookupResult is non-empty, it is assumed to describe a member which
12304/// will be invoked. Otherwise, the function will be found via argument
12305/// dependent lookup.
12306/// CallExpr is set to a valid expression and FRS_Success returned on success,
12307/// otherwise CallExpr is set to ExprError() and some non-success value
12308/// is returned.
12309Sema::ForRangeStatus
12310Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
12311 SourceLocation RangeLoc, VarDecl *Decl,
12312 BeginEndFunction BEF,
12313 const DeclarationNameInfo &NameInfo,
12314 LookupResult &MemberLookup,
12315 OverloadCandidateSet *CandidateSet,
12316 Expr *Range, ExprResult *CallExpr) {
12317 CandidateSet->clear();
12318 if (!MemberLookup.empty()) {
12319 ExprResult MemberRef =
12320 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12321 /*IsPtr=*/false, CXXScopeSpec(),
12322 /*TemplateKWLoc=*/SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012323 /*FirstQualifierInScope=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012324 MemberLookup,
Aaron Ballman6924dcd2015-09-01 14:49:24 +000012325 /*TemplateArgs=*/nullptr, S);
Sam Panzer0f384432012-08-21 00:52:01 +000012326 if (MemberRef.isInvalid()) {
12327 *CallExpr = ExprError();
12328 Diag(Range->getLocStart(), diag::note_in_for_range)
12329 << RangeLoc << BEF << Range->getType();
12330 return FRS_DiagnosticIssued;
12331 }
Craig Topperc3ec1492014-05-26 06:22:03 +000012332 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
Sam Panzer0f384432012-08-21 00:52:01 +000012333 if (CallExpr->isInvalid()) {
12334 *CallExpr = ExprError();
12335 Diag(Range->getLocStart(), diag::note_in_for_range)
12336 << RangeLoc << BEF << Range->getType();
12337 return FRS_DiagnosticIssued;
12338 }
12339 } else {
12340 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000012341 UnresolvedLookupExpr *Fn =
Craig Topperc3ec1492014-05-26 06:22:03 +000012342 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
Sam Panzer0f384432012-08-21 00:52:01 +000012343 NestedNameSpecifierLoc(), NameInfo,
12344 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000012345 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000012346
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012347 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000012348 CandidateSet, CallExpr);
12349 if (CandidateSet->empty() || CandidateSetError) {
12350 *CallExpr = ExprError();
12351 return FRS_NoViableFunction;
12352 }
12353 OverloadCandidateSet::iterator Best;
12354 OverloadingResult OverloadResult =
12355 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12356
12357 if (OverloadResult == OR_No_Viable_Function) {
12358 *CallExpr = ExprError();
12359 return FRS_NoViableFunction;
12360 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012361 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Craig Topperc3ec1492014-05-26 06:22:03 +000012362 Loc, nullptr, CandidateSet, &Best,
Sam Panzer0f384432012-08-21 00:52:01 +000012363 OverloadResult,
12364 /*AllowTypoCorrection=*/false);
12365 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12366 *CallExpr = ExprError();
12367 Diag(Range->getLocStart(), diag::note_in_for_range)
12368 << RangeLoc << BEF << Range->getType();
12369 return FRS_DiagnosticIssued;
12370 }
12371 }
12372 return FRS_Success;
12373}
12374
12375
Douglas Gregorcd695e52008-11-10 20:40:00 +000012376/// FixOverloadedFunctionReference - E is an expression that refers to
12377/// a C++ overloaded function (possibly with some parentheses and
12378/// perhaps a '&' around it). We have resolved the overloaded function
12379/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000012380/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000012381Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000012382 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000012383 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012384 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12385 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012386 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012387 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012388
Douglas Gregor51c538b2009-11-20 19:42:02 +000012389 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012390 }
12391
Douglas Gregor51c538b2009-11-20 19:42:02 +000012392 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012393 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12394 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012395 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000012396 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000012397 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000012398 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000012399 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012400 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012401
12402 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000012403 ICE->getCastKind(),
Craig Topperc3ec1492014-05-26 06:22:03 +000012404 SubExpr, nullptr,
John McCall2536c6d2010-08-25 10:28:54 +000012405 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012406 }
12407
Douglas Gregor51c538b2009-11-20 19:42:02 +000012408 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000012409 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000012410 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012411 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12412 if (Method->isStatic()) {
12413 // Do nothing: static member functions aren't any different
12414 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000012415 } else {
Alp Toker028ed912013-12-06 17:56:43 +000012416 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000012417 // UnresolvedLookupExpr holding an overloaded member function
12418 // or template.
John McCall16df1e52010-03-30 21:47:33 +000012419 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12420 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000012421 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012422 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012423
John McCalld14a8642009-11-21 08:51:07 +000012424 assert(isa<DeclRefExpr>(SubExpr)
12425 && "fixed to something other than a decl ref");
12426 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12427 && "fixed to a member ref with no nested name qualifier");
12428
12429 // We have taken the address of a pointer to member
12430 // function. Perform the computation here so that we get the
12431 // appropriate pointer to member type.
12432 QualType ClassType
12433 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12434 QualType MemPtrType
12435 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12436
John McCall7decc9e2010-11-18 06:31:45 +000012437 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12438 VK_RValue, OK_Ordinary,
12439 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012440 }
12441 }
John McCall16df1e52010-03-30 21:47:33 +000012442 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12443 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012444 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012445 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012446
John McCalle3027922010-08-25 11:45:40 +000012447 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012448 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000012449 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012450 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012451 }
John McCalld14a8642009-11-21 08:51:07 +000012452
12453 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000012454 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012455 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCalle66edc12009-11-24 19:00:30 +000012456 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000012457 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12458 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000012459 }
12460
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012461 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12462 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012463 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012464 Fn,
John McCall113bee02012-03-10 09:33:50 +000012465 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012466 ULE->getNameLoc(),
12467 Fn->getType(),
12468 VK_LValue,
12469 Found.getDecl(),
12470 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012471 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012472 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12473 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000012474 }
12475
John McCall10eae182009-11-30 22:42:35 +000012476 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000012477 // FIXME: avoid copy.
Craig Topperc3ec1492014-05-26 06:22:03 +000012478 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
John McCall2d74de92009-12-01 22:10:20 +000012479 if (MemExpr->hasExplicitTemplateArgs()) {
12480 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12481 TemplateArgs = &TemplateArgsBuffer;
12482 }
John McCall6b51f282009-11-23 01:53:49 +000012483
John McCall2d74de92009-12-01 22:10:20 +000012484 Expr *Base;
12485
John McCall7decc9e2010-11-18 06:31:45 +000012486 // If we're filling in a static method where we used to have an
12487 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000012488 if (MemExpr->isImplicitAccess()) {
12489 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012490 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12491 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012492 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012493 Fn,
John McCall113bee02012-03-10 09:33:50 +000012494 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012495 MemExpr->getMemberLoc(),
12496 Fn->getType(),
12497 VK_LValue,
12498 Found.getDecl(),
12499 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012500 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012501 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
12502 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000012503 } else {
12504 SourceLocation Loc = MemExpr->getMemberLoc();
12505 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000012506 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000012507 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000012508 Base = new (Context) CXXThisExpr(Loc,
12509 MemExpr->getBaseType(),
12510 /*isImplicit=*/true);
12511 }
John McCall2d74de92009-12-01 22:10:20 +000012512 } else
John McCallc3007a22010-10-26 07:05:15 +000012513 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000012514
John McCall4adb38c2011-04-27 00:36:17 +000012515 ExprValueKind valueKind;
12516 QualType type;
12517 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12518 valueKind = VK_LValue;
12519 type = Fn->getType();
12520 } else {
12521 valueKind = VK_RValue;
Yunzhong Gaoeba323a2015-05-01 02:04:32 +000012522 type = Context.BoundMemberTy;
12523 }
12524
12525 MemberExpr *ME = MemberExpr::Create(
12526 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
12527 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
12528 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind,
12529 OK_Ordinary);
12530 ME->setHadMultipleCandidates(true);
12531 MarkMemberReferenced(ME);
12532 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012533 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012534
John McCallc3007a22010-10-26 07:05:15 +000012535 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000012536}
12537
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012538ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000012539 DeclAccessPair Found,
12540 FunctionDecl *Fn) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000012541 return FixOverloadedFunctionReference(E.get(), Found, Fn);
Douglas Gregor3e1e5272009-12-09 23:02:17 +000012542}